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

Amit Merchant

A blog on PHP, JavaScript, and more

The new @class Blade directive in Laravel 8.x

Sometimes, the biggest sign that shows that a framework is maturing is when it has multiple ways of doing the same thing. Laravel, being one of these frameworks, is no exception.

For instance, 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-red conditionally, you can do it like so.

<div {{ $attributes->class([
    'p-4', 
    'bg-red' => $hasError
]) }}>
    Welp! something gone wrong.
</div>

As you can tell, the bg-red class in here is driven by the value of $hasError. Meaning, the class() would only include the bg-red class when the $hasError is true.

This is fine and you wouldn’t mind keep on using it. But it’s kind of verbose and doesn’t look tidy.

And that is when a new @class Blade directive comes into the picture.

The @class directive

In the recent release of Laravel, this PR tries to add a @class Blade directive which does essentially the same thing which I mentioned previously but in a less verbose manner. So, here’s how the previous example would look like using the @class directive like so.

<div @class([
    'p-4', 
    'bg-red' => $hasError
])>
    Welp! something gone wrong.
</div>

As you can see, the @class directive does exactly the same job as the $attributes->class() method but in a compact manner. And since, it’s a Blade directive, it gets to blend in into the Blade ecosystem pretty nicely.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), 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? Consider leaving a

Tip

👋 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?