MasterPHP.in
Try Compiler →
Laravel Tutorial

Building a Reusable UI Kit in Laravel Blade (Navbar, Alerts, Cards)


Look at your invoice app after the last seven lessons. You have a layout, a status badge, a money label and a button component, and the pages are styled with Tailwind. But the pieces were built one at a time, and it shows. The success message in the layout has its own long list of classes. The invoice list uses a class-based card, the detail page uses plain <div> boxes, and the navbar is still a few links in the layout file.

Now imagine a second developer joins and builds the Clients page. They have no idea which colours mean “success”, how big a card header should be, or which button style is the primary one. They copy a block from some page and change it. A month later, every page looks slightly different, and changing the brand colour means a search across the whole project.

The fix is a small UI kit: a set of components that decide how things look, in one place. In this lesson you will finish Chapter 7 by building a button, an alert, a card and a responsive navbar from the tools you already know, and by using them to rebuild the invoice pages.

The Problem: Styled Pages Without a System

Here is the kind of block that gets pasted across pages when there is no kit:

<div class="mb-4 rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800">
    Invoice saved.
</div>

<a href="/invoices/create"
   class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">
    New invoice
</a>

Each block looks fine alone. The trouble is that you will write the same 15 classes again on the next page, and one developer will write px-3 while another writes px-4. Nothing is wrong with Tailwind here. The missing piece is a single place that owns the decision.

 

What Is a UI Kit?

A UI kit is a small collection of components that cover the building blocks of your interface. It is not a package to install. It is a folder in your project, and the components in it follow a few rules:

  • They are small. One component does one visual job, such as a button or an alert.
  • They use props for decisions. Choices like variant="danger" or type="success" are props. Everything else comes from the page.
  • They carry the attribute bag. The root element prints $attributes, so pages can add id, class, Alpine directives and more.
  • They use slots for content. The page decides what text appears inside, and the component decides how it looks.
  • They do not fetch data. No queries, no service calls. They display what they receive.
  • They write full Tailwind class names. As you learned in the last lesson, Tailwind cannot read classes built from PHP strings.

This is how the finished kit will look in your project:

resources/views/components/
    alert.blade.php            <x-alert>
    button.blade.php           <x-button>
    money.blade.php            <x-money>          (from an earlier lesson)
    nav-link.blade.php         <x-nav-link>
    navbar.blade.php           <x-navbar>
    status-badge.blade.php     <x-status-badge>   (from an earlier lesson)
    card/
        index.blade.php        <x-card>
        header.blade.php       <x-card.header>
        body.blade.php         <x-card.body>
        footer.blade.php       <x-card.footer>

The badge and money components already exist, so you only need to build the rest.

 

The Button

You have already used a basic button. Replace resources/views/components/button.blade.php with a version that has real variants and can also render as a link:

@props(['variant' => 'primary', 'href' => null])

@php
    $base = 'inline-flex items-center rounded-md px-4 py-2 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50';

    $styles = match ($variant) {
        'secondary' => 'border border-gray-300 bg-white text-gray-700 hover:bg-gray-50',
        'danger'    => 'bg-red-600 text-white hover:bg-red-700',
        default     => 'bg-indigo-600 text-white hover:bg-indigo-700',
    };
@endphp

@if ($href)
    <a href="{{ $href }}" {{ $attributes->class([$base, $styles]) }}>{{ $slot }}</a>
@else
    <button {{ $attributes->merge(['type' => 'button'])->class([$base, $styles]) }}>{{ $slot }}</button>
@endif

A button that navigates should be an <a> tag, and a button that acts should be a <button>. Giving the component an optional href lets one tag handle both, so every action on the site looks identical:

<x-button :href="route('invoices.create')">New invoice</x-button>
<x-button variant="secondary">Save draft</x-button>
<x-button variant="danger" type="submit">Delete</x-button>

The default type="button" is deliberate. A button inside a form with no type submits the form, so the safe default is “do nothing”, and a page asks for type="submit" when it means it.

 

The Alert

An alert shows a message with a colour that matches its meaning. It also needs a close button sometimes, and Alpine handles that without any extra JavaScript file. Create resources/views/components/alert.blade.php:

@props(['type' => 'info', 'dismissible' => false])

@php
    $styles = match ($type) {
        'success' => 'border-green-200 bg-green-50 text-green-800',
        'error'   => 'border-red-200 bg-red-50 text-red-800',
        'warning' => 'border-yellow-200 bg-yellow-50 text-yellow-800',
        default   => 'border-blue-200 bg-blue-50 text-blue-800',
    };
@endphp

<div x-data="{ show: true }"
     x-show="show"
     role="alert"
     {{ $attributes->class(['flex items-start justify-between gap-4 rounded-md border px-4 py-3 text-sm', $styles]) }}>
    <div>{{ $slot }}</div>

    @if ($dismissible)
        <button type="button" @click="show = false" aria-label="Close" class="font-bold leading-none">
            &times;
        </button>
    @endif
</div>

Three details are worth noticing. The match returns complete class strings, so Tailwind can find them. The role="alert" attribute helps screen readers announce the message. And the close button exists only when the page asks for it, using the dismissible prop.

Use it like this:

<x-alert type="success" :dismissible="true">Invoice 1001 saved.</x-alert>
<x-alert type="warning">Two invoices are overdue.</x-alert>

Notice the colon on :dismissible="true". The prop needs a real boolean, and the Common Mistakes section shows what goes wrong without it.

 

The Card

A card is a family of pieces: a wrapper, a header, a body and a footer. This is the folder-with-index pattern from the Anonymous Components lesson. Start with resources/views/components/card/index.blade.php:

<div {{ $attributes->class(['overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm']) }}>
    {{ $slot }}
</div>

Then create the three parts. First card/header.blade.php:

<div {{ $attributes->class(['flex items-center justify-between gap-3 border-b border-gray-200 px-5 py-3 font-semibold text-gray-900']) }}>
    {{ $slot }}
</div>

Then card/body.blade.php:

<div {{ $attributes->class(['px-5 py-4 text-sm text-gray-700']) }}>
    {{ $slot }}
</div>

And card/footer.blade.php:

<div {{ $attributes->class(['flex items-center justify-end gap-2 border-t border-gray-200 bg-gray-50 px-5 py-3']) }}>
    {{ $slot }}
</div>

Each part owns its own spacing, so a page can use only the pieces it needs. A card with only a body is valid, and so is one with all three. The header uses justify-between, so a title on the left and a badge on the right line up without any extra markup.

This replaces the class-based <x-invoice.card> from the Components lesson. It is more flexible, because the page decides which parts exist, and there is no PHP class to maintain. You can delete the old class and view once the pages use the new card.

 

The Navbar

The Nav Link

The navbar needs links that know whether they are the current page. Create resources/views/components/nav-link.blade.php:

@props(['active' => false])

<a {{ $attributes->class([
    'block rounded-md px-3 py-2 text-sm font-medium',
    'bg-indigo-50 text-indigo-700' => $active,
    'text-gray-600 hover:bg-gray-50 hover:text-indigo-600' => ! $active,
]) }}
   @if ($active) aria-current="page" @endif>
    {{ $slot }}
</a>

The class() method from the Anonymous Components lesson handles the two states. The page decides what “active” means and passes it in, so the component never needs to know about your routes. The href is not a prop, so it flows through the attribute bag onto the <a> tag.

 

The Navbar Component

Now the navbar itself, resources/views/components/navbar.blade.php. It shows links in a row on wide screens and behind a Menu button on phones:

@props(['brand' => config('app.name')])

<header x-data="{ open: false }" {{ $attributes->class(['border-b border-gray-200 bg-white']) }}>
    <div class="mx-auto flex max-w-5xl flex-wrap items-center justify-between px-4 py-3">
        <a href="{{ url('/') }}" class="text-lg font-bold text-gray-900">{{ $brand }}</a>

        <button type="button"
                @click="open = ! open"
                class="rounded-md px-3 py-1 text-sm text-gray-600 md:hidden"
                aria-label="Toggle menu">
            <span x-text="open ? 'Close' : 'Menu'"></span>
        </button>

        <nav :class="open ? 'flex' : 'hidden'"
             class="w-full flex-col gap-1 pt-3 md:flex md:w-auto md:flex-row md:items-center md:gap-2 md:pt-0">
            {{ $slot }}

            @isset($actions)
                <div class="md:ml-2">{{ $actions }}</div>
            @endisset
        </nav>
    </div>
</header>

The behaviour comes from these pieces:

  • x-data="{ open: false }" tracks whether the mobile menu is open.
  • The Menu button has md:hidden, so it exists only on small screens.
  • The nav uses :class to switch between flex and hidden on phones. On medium screens and larger, md:flex takes over and the menu is always visible.
  • flex-wrap and w-full push the links onto their own row below the brand on a phone.

The component uses :class rather than x-show on purpose. The x-show directive sets an inline display: none, which would also hide the menu on desktop and ignore md:flex. Switching classes keeps Tailwind in charge of the breakpoints.

The links arrive through the default slot, and an optional named slot called actions holds a button on the right. The navbar contains no routes and no page names, so it works in any project. Login and logout links will join it in the Authentication chapter.

 

Using the Kit in the Layout

Now update layouts/app.blade.php. The whole header block becomes one component, and the flash messages become alerts:

<body class="bg-gray-50 text-gray-800">
    <x-navbar>
        <x-nav-link :href="route('invoices.index')" :active="request()->routeIs('invoices.*')">
            Invoices
        </x-nav-link>

        <x-slot:actions>
            <x-button :href="route('invoices.create')">New invoice</x-button>
        </x-slot:actions>
    </x-navbar>

    <main class="mx-auto max-w-5xl px-4 py-8">
        @session('status')
            <x-alert type="success" :dismissible="true" class="mb-4">{{ $value }}</x-alert>
        @endsession

        @session('error')
            <x-alert type="error" :dismissible="true" class="mb-4">{{ $value }}</x-alert>
        @endsession

        @yield('content')
    </main>

    <footer class="py-6 text-center text-sm text-gray-500">
        &copy; {{ date('Y') }} MasterPHP Traders
    </footer>

    @stack('scripts')
</body>

The layout is shorter and easier to read than before, and it describes the page in plain words. The @extends approach still works with components inside it, exactly as the course planned.

 

Putting It Together: The Invoice Pages

Rebuild the list page using the card. Each invoice becomes a small card, and the empty state becomes an alert:

@extends('layouts.app')

@section('title', 'Invoices')

@section('content')
    <h2 class="mb-4 text-2xl font-bold">Invoices</h2>

    @forelse ($invoices as $number => $invoice)
        <x-card class="mb-4">
            <x-card.header>
                <a href="{{ route('invoices.show', $number) }}" class="hover:text-indigo-600">
                    Invoice {{ $number }}
                </a>
                <x-status-badge :status="$invoice['status']" />
            </x-card.header>

            <x-card.body class="flex items-center justify-between">
                <span>{{ $invoice['client'] }}</span>
                <x-money :amount="$invoice['total']" class="font-semibold" />
            </x-card.body>
        </x-card>
    @empty
        <x-alert type="info">No invoices yet. Create your first invoice.</x-alert>
    @endforelse
@endsection

Now the invoice summary on the detail page, with a footer that holds the actions:

<x-card>
    <x-card.header>
        Invoice {{ $number }}
        <x-status-badge :status="$invoice['status']" />
    </x-card.header>

    <x-card.body>
        <p>Client: {{ $invoice['client'] }}</p>
        <p class="mt-1">Total: <x-money :amount="$invoice['total']" class="font-semibold" /></p>
    </x-card.body>

    <x-card.footer>
        <x-button variant="secondary" :href="route('invoices.index')">Back</x-button>
        <x-button>Pay now</x-button>
    </x-card.footer>
</x-card>

Compare this with the original pages. There is not a single long class list, and every colour, spacing and border comes from the kit. If the owner wants rounder corners on every card, you change one file.

 

A Living Style Guide Page

A kit is easier to keep consistent when you can see every component on one page. Create a simple page that shows each variant, and expose it only while you are developing:

// routes/web.php
if (app()->environment('local')) {
    Route::view('/ui-kit', 'ui-kit');
}

The Route::view() helper is the one you saw in the Redirect, View & Fallback Routes lesson. The if means the page exists on your machine, where APP_ENV is local, and returns a 404 on the live site. The view resources/views/ui-kit.blade.php extends your layout and lists the components:

@extends('layouts.app')

@section('title', 'UI Kit')

@section('content')
    <div class="flex gap-2">
        <x-button>Primary</x-button>
        <x-button variant="secondary">Secondary</x-button>
        <x-button variant="danger">Danger</x-button>
    </div>

    <div class="mt-6 space-y-3">
        <x-alert type="success">Success message</x-alert>
        <x-alert type="error">Error message</x-alert>
        <x-alert type="warning">Warning message</x-alert>
        <x-alert type="info">Info message</x-alert>
    </div>
@endsection

When someone adds a new variant, they add a line here, and the team can check how it looks next to the others.

 

Rules for a Healthy Kit

A kit stays useful only if it stays small and predictable. Follow these habits:

  • Add a component when you have copied the same markup a third time, not before.
  • Keep prop lists short. If a component needs eight props, it is probably two components.
  • Never hard-code routes, page names or database values inside a kit component. Pass them in through props and slots.
  • Always print {{ $attributes }} on the root element, so pages can adjust spacing and add attributes.
  • Name components after what they are (alert, card), not where they are used (invoice-success-box).

 

Common Mistakes

Mistake 1: Component Name Typos

<x-card.headr>Invoice 1001</x-card.headr>

Laravel cannot find a file with that name, and stops with:

InvalidArgumentException: Unable to locate a class or view for component [card.headr].

Check the tag against the file path. card/header.blade.php is x-card.header.

 

Mistake 2: Passing “false” as a Plain String

<x-alert dismissible="false">Saved</x-alert>

Without a colon, Blade passes the text false, and in PHP the non-empty string 'false' counts as true. The close button appears, and no error warns you. Write :dismissible="false" or simply leave the prop out.

 

Mistake 3: Using x-show for a Responsive Menu

<nav x-show="open" class="md:flex">

On a desktop screen, open is false, so Alpine hides the menu with an inline style, and md:flex cannot bring it back. The links vanish on large screens. Switch classes with :class, as the navbar does, and let Tailwind handle the breakpoints.

 

Mistake 4: Hard-Coding Page Details in a Kit Component

<a href="{{ route('invoices.index') }}">Invoices</a>

If this link sits inside navbar.blade.php, the navbar only works for the invoice app, and it needs editing for every new section. Pass links through the slot, as the layout does.

 

Mistake 5: Forgetting $attributes on the Root Element

<div class="rounded-lg border bg-white">{{ $slot }}</div>

A page writes <x-card class="mb-4"> and the margin never appears, because the bag was never printed. There is no error. Use {{ $attributes->class([...]) }} on every kit component.

 

Mistake 6: Expecting Page Classes to Override Component Classes

A page adds p-2 to a card that already has p-5. Both classes reach the HTML, but Tailwind decides which one wins by the order of its generated CSS, not by the order in your class attribute. The result may not be what you expect. Use the kit’s own props for important differences, or leave the property out of the base component and let pages supply it.

 

Quick Summary

  • A UI kit is a folder of small Blade components that decide how your interface looks, so pages describe content and not styling.
  • Each component should do one visual job, use props for choices, slots for content, and print $attributes on its root element.
  • Keep kit components free of queries, routes and page-specific data.
  • Use full Tailwind class names inside match expressions so Tailwind can find them.
  • The button handles variants and can render as a link when it receives an href.
  • The alert uses a type prop for colour and Alpine for an optional close button.
  • The card is a folder with index, header, body and footer files, so pages use only the parts they need.
  • The navbar switches classes with Alpine on phones and relies on md: classes for desktop, and takes its links through slots.
  • Pass booleans with a colon, such as :dismissible="true", because the plain string "false" is truthy.
  • A development-only /ui-kit page shows every variant side by side.

 

What’s Next

Your frontend now has a layout, a design system and small interactions, but all your invoices still come from arrays written by hand. In the next chapter, you will start working with real data. The first lesson, Database Configuration: SQLite & MySQL, shows how Laravel connects to a database, how the connection settings in .env and config/database.php fit together, and how to switch between SQLite and MySQL safely.

Frequently Asked Questions

Keep general building blocks like buttons, alerts and cards in resources/views/components, and group related pieces in folders, such as card/header and card/body. Many teams also create a ui folder for the shared kit and separate folders for feature components, like invoice/row. The dotted tag name always follows the folder path.
Yes. Libraries built for Tailwind can give you good-looking pieces quickly, and you can wrap them in your own Blade components to keep one consistent interface. Building a small kit yourself is still valuable, because you learn how props, slots and the attribute bag work, and you control the final look.
Print the attribute bag with class() on the root element, so a page can add extra classes. Remember that Tailwind decides which class wins by its CSS order, not by the order in your HTML. For real differences, use a prop such as variant, or leave that property out of the base component.
Use the session directive in your layout to read the flash value, and place it inside an alert component, for example with type success. Because the layout is shared, every page that redirects with a status message shows the alert automatically. You can add another block for error messages in the same way.
Laravel lets you render a snippet of Blade inside a test with the blade method and check the output with assertions like assertSee. This is handy for checking that an alert shows its message or that a button uses the right classes. You will learn the testing tools in the Testing chapter.

Share this tutorial