Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Merge attributes in blade components in Laravel 7.x

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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?