Posts Learn Components Snippets Categories Tags Tools new About
/

Laravel Blade @class Directive

Learn what Laravel Blade @class directive is and how to use it to conditionally comile class into string

Created on Jul 23, 2021

124 views

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:

Blade @class Directive Example
@php
    $isActive = false;
    $hasError = true;
@endphp

<span @class([
    'p-4',
    'font-bold' => $isActive,
    'text-gray-500' => ! $isActive,
    'bg-red' => $hasError,
])></span>

<span class="p-4 text-gray-500 bg-red"></span>

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Laravel Blade @class Directive

)