Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you explain how to use slots in Blade components
    Laravel Blade components slots Blade templates web development PHP


Can you explain how to use slots in Blade components


Here is a concise explanation of how to use slots in Laravel Blade components:

Slots allow you to define placeholders in your Blade components that can be filled with content from the parent view. This makes your components more flexible and reusable.

To define a slot in your component, use the `< $slot >` directive in the component's Blade template. This will serve as the placeholder for the content that will be passed from the parent view.

For example, in your `alert.blade.php` component:

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

To use this component and pass content to the slot, use the `@component` directive in your parent view:

html
@component('components.alert')
    <strong>Whoops!</strong> Something went wrong!
@endcomponent

The content between the `@component` and `@endcomponent` directives will be injected into the `$slot` variable in the `alert` component [1].

You can also define named slots if you need multiple placeholders in your component. To do this, use the `@slot` directive to define the slot, and then reference it using the slot name in the component template [2][3]:

html
<!-- alert.blade.php -->
<div class="alert alert-danger">
    <div class="alert-title">{{ $title }}</div>
    {{ $slot }}
</div>

html
<!-- parent-view.blade.php -->
@component('components.alert')
    @slot('title')
        Forbidden
    @endslot
    You are not allowed to access this resource!
@endcomponent

This allows you to pass different content to different parts of the component, making it more flexible and reusable [4].

Citations:
[1] https://www.youtube.com/watch?v=D4Y6spYNvnc
[2] https://alishoff.com/blog/386
[3] https://spatie.be/docs/laravel-blade-x/v2/basic-usage/using-slots
[4] https://wpwebinfotech.com/blog/laravel-blade-components/
[5] https://laravel.com/docs/5.5/blade