DEV Community

Cover image for Conditional Classes Blade Directives in Laravel
Suresh Ramani
Suresh Ramani

Posted on • Originally published at

Conditional Classes Blade Directives in Laravel

New in Laravel 8.51: @class Blade directive to add true/false conditions on whether some CSS class should be added.

The @class directive conditionally compiles a CSS class string. The directive accepts an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression. If the array element has a numeric key, it will always be included in the rendered class list:

    $hasError = true;

<span @class([
    'bg-red' => $hasError,
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this blog.

Top comments (2)

bobbyiliev profile image
Bobby Iliev

Nice, very cool tip! I should upgrade to Laravel 8.51

bdelespierre profile image
Benjamin Delespierre