Conditional Classes Blade Directives in Laravel

Aug 22, 2022 . Admin

Hello Friends,

This article will give you example of Conditional Classes Blade Directives in Laravel?. I explained simply step by step laravel blade dynamic class. we will help you to give example of how to add class conditionally in laravel blade. We will look at example of if condition in laravel blade class. follow bellow step for laravel blade class if condition.

This is simple but I can't seem to be able to do it with blade and I usually go back to laravel for this but, since I can't declare a new laravel variable with blade (without printing it, that is) how should I change a simple class name if a certain condition is met? Take this example of a link, I just want to add the class when condition is true

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.

so let's start with following examples

Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Laravel Blade Conditional Class Example 1 :
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Conditional Classes Blade Directives in Laravel</title>
</head>
<body>
    <div class="container">
        @php
            $isActive = false;
        @endphp
         
        <span @class([
            'p-4',
            'bg-pink-900 text-green-200' => $isActive,
            'bg-red-500 text-white' => ! $isActive
        ])></span>
    </div>
</body>
</html>
Output:
<span class="p-4 bg-red-500 text-white"> </span>
Example 2 :
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Conditional Classes Blade Directives in Laravel</title>
</head>
<body>
    <div class="container">
        <span class="p-4 text-gray-500 
            @if ($isActive)
                bg-pink-900 text-green-200
            @else
                bg-red-500 text-white
            @endif
        "> </span>
    </div>
</body>
</html>
Output:
<span class="p-4 text-gray-500 bg-pink-900 text-green-200"></span>
Example 3 :
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Conditional Classes Blade Directives in Laravel?</title>
</head>
<body>
    <div class="container">
        <span class="p-4 text-gray-500 {{ $isActive ? 'font-bold' : 'font-normal' }}"></span>
    </div>
</body>
</html>
Output:
<span class="p-4 text-gray-500 font-bold"></span>

now it works...

I hope it can help you...

#Laravel