Named slots in Blade components in Laravel 7.x

Amit Merchant · April 14, 2020 ·

The new Blade components in Laravel 7 are great. They provide an easy way of defining blade components in a Vue-like tag aliases. One of the nice features of Blade components are slots.

Basically, what slot allows you to do is inject dynamic content into the blade component. For instance, if we’ve this sidebar component…

<!-- /resources/views/components/sidebar.blade.php -->

<div class="collapse list-unstyled">
    <!-- want to fill in dynmic content here -->
</div>

And we want to inject some dynamic content inside the <div>, we can achieve this using slots like so.

<!-- /resources/views/components/sidebar.blade.php -->

<div class="collapse list-unstyled">
    {{ $slot }}
</div>

And now, we can pass content to the slot by injecting content into the component like so.

<x-sidebar>
    <ul>
        <li>Home</li>
        <li>Articles</li>
        <li>About</li>
    </ul>
</x-sidebar>

All the content inside the <x-sidebar> tags will get slotted in the $slot variable of the component where it is used.

Now, what if we want to use multiple slots inside of the component? Well, we can do this by using “Named” slots. And it seems like the inspiration is taken from the similar concept in Vue.js.

Named Slots

At its heart, if you want to use multiple slots inside of a component, you can use a <x-slot> tag and pass in a name attribute to it. For instance, in our previous example, if we want to insert a user avatar to the component, we can add a <x-slot> tag with attribute name="avatar" like so.

<x-sidebar>
    <x-slot name="avatar">
        <img src="/image/user-avatar.png" />
    </x-slot>

    <ul>
        <li>Home</li>
        <li>Articles</li>
        <li>About</li>
    </ul>
</x-sidebar>

…Which can be further accessible in the component as a $avatar variable like so.

<!-- /resources/views/components/sidebar.blade.php -->

<div>
    {{ $avatar }}
</div>

<div class="collapse list-unstyled">
    {{ $slot }}
</div>

This way you can add multiple slots into your component which can come handy in certain situations like the one I’ve described above.

Twitter, Facebook

Hi there! I'm Amit. I write articles about all things web development. If you like what I write, buy me a coffee. I'd highly appreciate that. Cheers!

Newsletter

Follow me on Twitter as @amit_merchant