Laravel How to use @class Blade Directive

Hello Artisan, today I'll show you how to use the new blade directive called @class. This is useful when we want to add class based on condition where doesn't require any manual @if @endif directive. So, let's see how we can use @class directive and remove the complexity of using @if @endif directive.

Table of Contents

  1. Example 1
  2. Example 2

Example 1

If we back in the previous moments, where if we need any class to be added, we used to use so called @if @endif directive. Like below

@if (auth()->check())
<span class="badge badge-success">Logged In</span>
@else
<span class="badge badge-danger">Inactive</span>
@endif

Which is tidy and too much inflexible for use. But if we write want to show same badge with @class directive, it will be nice and shorthand for use. See the example below  .

<span 
@class([
    'badge', 
    'badge-success'=> auth()->check(),
    'badge-danger' => !auth()->check(),
    ])>user
</span>

Example 2

In most of the time we used to active the sidebar link based on the route. We can also achieve the result in prettier way like below

<li>
    <a href="{{ route('dashboard') }}" @class(['active'=> request()->is('dashboard') ])>Dashboard</a>
</li>

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. ๐Ÿ™‚