The @class Blade Directive in Laravel 8.51x

The @class Blade Directive in Laravel 8.51x

Hello Artisans,

How are you doing? Do you know, on July 21st, 2021 Laravel has Released a version 8.51x. In this version they add stack traces included in failed HTTP tests, a new blade (@class)directive to render a CSS class string dynamically.

The @class Blade Directive in Laravel 8.51x

In this tutorial, I will discuss with you The @class Blade Directive in Laravel 8.51x with a couple of examples.

@class Blade Directive
@class Blade Directive

Well, Conditionally class add is one of the common things in our all projects. Bellow, I will show you an example of how to add a class by conditions.

Route::view('class', 'testing.class', [
    'isActive' => true,

Let’s assume we have a route (class). When we hit this route it will return us a view that is inside my testing folder. I have passed a boolean value in the view file.

        class="text-center text-4xl font-normal @if ($isActive)
        bg-pink-900 text-green-200
        bg-red-500 text-white
Conditional Class

Well, you can see that inside H1 class I’ve checked a condition that is if ($isActive) is true then “bg-pink-900 text-green-200” will be rendered on the other hand “ bg-red-500 text-white” will be rendered. Simple, right?

Now think if we have to check more and more conditions for add dynamic classes, It will look messy. Well, look below examples of how beautifully we add class by conditions using the @class Blade Directive

            'text-center text-4xl font-normal', // common classes 
            'bg-pink-900 text-green-200' => $isActive,
            'bg-red-500 text-white' => !$isActive
  >Conditional Class</h1>

Look how organized our code is. RIght? If we have more conditions we can add sequentially like that.

Hope you will enjoy this tutorial.

Read More: What is Circuit Breaker Design Pattern? How to Use Circuit Breaker Design Pattern in Laravel

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m an Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website:

View all posts by Anisur Rahman Shahin →

Leave a Reply

Your email address will not be published.