In this tutorial we will see how to use @class blade directive in laravel 9. The @class directive conditionally compiles a CSS class string. @class directive accepts an array of classes. We can show true false value with style color using @class.
Example 1
If we want show active user with green and inactive user red we can use @if @endif blade directive.
@php
$active = true;
$inActive = false;
@endphp
@if ($active)
<span class="p-2 text-green-500 rounded">user</span>
@else
<span class="p-2 text-red-500 rounded">user</span>
@endif
Show active user with green and inactive user red @class blade directive.
<span
@class([
'p-2',
'text-green-500'=> $active,
'bg-red-500' => $inActive,
])>user
</span>
Example 2
Using @class to style condition selected value.
<select class="block w-full mt-1" name="status">
<option value="published" @selected($blog->status == 'published')
@class([
'bg-purple-600 text-white' => $blog->status == 'published'
])>Published</option>
<option value="draft" @selected($blog->status == 'draft')
@class([
'bg-purple-600 text-white' => $blog->status == 'draft'
])
>Draft</option>
<option value="archived" @selected($blog->status == 'archived')
@class([
'bg-purple-600 text-white' => $blog->status == 'archived'
])
>Archived</option>
</select>
Example 3
We can use @class to active link class with tailwind css navbar links
<li>
<a href="{{ route('laravel') }}" @class(['text-blue-600'=> request()->is('laravel') ])>Laravel</a>
</li>