Introducing

How to Use @class Blade Directive in Laravel


For example, in Blade templates, if you want to add HTML classes conditionally, you can do this by using the class method of the component’s “attribute bag”.

The attribute bag is available through the $attributes variable inside the

Blade component

So, if you want to add, for instance, an error class bg-blue conditionally, you can do it like so.

<div {{ $attributes->class([
    'p-2', 
    'bg-blue' => $hasError
]) }}>
    Oops! Something gone wrong.
</div>

It looks kind of verbose and doesn’t look slick.

And that is when a

new @class Blade directive

comes into the picture.

So, here’s how the previous example would look like using the @class directive like so.

<div @class([
    'p-2', 
    'bg-blue' => $hasError
])>
Oops! Something gone wrong.
</div>
Something you may be interested:
Categories:
Tags:
Laravel @class
Blade directive
Laravel