Building Highly Reusable UI with Blade Components & Slots

· 2 min read

Blade Components are one of the most powerful features in Laravel, helping you organize your HTML markup and reuse UI elements easily and cleanly.

1. Class-based vs Anonymous Components

Anonymous Components

Best suited to static UIs that do not require complex data preparation logic. The component file is saved at resources/views/components/alert.blade.php:

<div class="alert alert-{{ $type }}">
    {{ $slot }}
</div>

Usage:

<x-alert type="error">
    Error: Unable to connect to the database!
</x-alert>

Class-based Components

Best suited when the component needs logic before rendering. Run the command php artisan make:component Alert. It creates 2 files:

  • app/View/Components/Alert.php
  • resources/views/components/alert.blade.php
namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    public $type;
    public $message;

    public function __construct($type, $message)
    {
        $this->type = $type;
        $this->message = $message;
    }

    public function render()
    {
        return view('components.alert');
    }
}

2. Managing Attributes with $attributes->merge()

When working with CSS frameworks like Tailwind, merging external classes passed into the component with default classes is a must.

Inside the component:

<button {{ $attributes->merge(['class' => 'bg-blue-500 text-white px-4 py-2 rounded font-bold']) }}>
    {{ $slot }}
</button>

When using the component, you can pass an additional class attribute and it will be safely merged:

<x-button class="hover:bg-blue-700 mt-4">
    Save Changes
</x-button>

3. Named Slots and Scoped Slots

Besides the default $slot variable, you can reuse complex blocks using Named Slots.

Component modal.blade.php:

<div class="modal">
    <div class="modal-header">
        {{ $title }}
    </div>
    <div class="modal-body">
        {{ $slot }}
    </div>
    <div class="modal-footer">
        {{ $actions }}
    </div>
</div>

Using the Modal:

<x-modal>
    <x-slot:title>
        Confirm Deletion
    </x-slot>

    Are you sure you want to delete this post?

    <x-slot:actions>
        <button>Cancel</button>
        <button class="text-red-500">Delete</button>
    </x-slot>
</x-modal>

Using a component structure keeps your layout files neat, clean, and easier to maintain than ever.

Comments