Merging Classes In Laravel Blade Components

Last updated 3rd December, 2023

You want to pass classes to your custom component that will merge with the classes that already exist on the component. Here's how you do it.

Pass Through The Classes

<x-announcement class="w-full my-12">
    <span class="text-slate-900">Are you perhaps short of a marble.</span>
</x-announcement>

Merging The Class Attributes

When you've added those class attributes to the component, all you have to do is tell Laravel that you want to merge those classes with some defaults:

// views/components/announcement.blade.php

<div {{ $attributes->merge(['class' => 'rounded-lg bg-gray-50 p-6 shadow-lg']) }}>
    {{ $slot }}
</div>

The Resulting Output

The resulting HTML should be the following:

<div class="w-full my-12 rounded-lg bg-gray-50 p-6 shadow-lg">
    <span class="text-slate-900">Are you perhaps short of a marble.</span>
</div>

This approach also works for any non-prop attribute passed to a Laravel component. If you want to know more about how this works - the docs are a great place to start!

Hope this helps 🤙

No comments yet…

DevInTheWild.

Login To Add Comments.

Want More Like This?

Subscribe to occasional updates.

Related Articles