Merge attributes in blade components in Laravel 7.x

Amit Merchant · April 7, 2020 ·

Blade component tags are a useful additions to the latest version of Laravel i.e. version 7. In Laravel 7, Blade components have been overhauled to allow tag based rendering, attribute management, component classes, inline view components, and more.

So, for instance, if you’ve following blade component for instance,

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

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

Then the component can be rendered in another Blade view using the component’s tag like so.

<x-alert>
    Default slot content...
</x-alert>

Here, everything between <x-alert> tag gets slotted in as $slot varible in the alert.blade.php.

Now, let’s take the following case where you also pass in a class class="mb-4" to the component tag as well.

<x-alert class="mb-4">
    Default slot content...
</x-alert>

You’d expect that the class “mb-4” will get merged with the “alert” and the result would be something like so.

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

But that’s not the expected output you’d get. That’s where $attributes property for Blade component comes into play.

$attributes property

At its heart, $attributes carry all the attributes passed into the component tags. So, let’s take the above example for instance by taking $attributes into it.

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

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

So, if pass in an another class into the tag like so.

<x-alert class="mb-4">
    Default slot content...
</x-alert>

The result will be,

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

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

As you can see, the classed didn’t merge. Instead, Laravel tried to create it’s own class attribute. So, in order to merge the additional values to the attributes, you’d use merge() method on $attributes like so.

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

<div {{ $attributes->merge(['class' => 'alert']) }}>
    {{ $slot }}
</div>

You’ll now get the desired result. i.e. a blade component having both the alert and mb-4 values merged together in class attribute.

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 @amit_merchant