Laravel Blade Conditional Class Example

10-Apr-2023

.

Admin

Laravel Blade Conditional Class Example

Hello Friends,

This tutorial will provide example of laravel blade conditional class example. This post will give you simple example of laravel blade dynamic class. I would like to share with you if condition in laravel blade class. I’m going to show you about laravel blade class if condition. So, let's follow few step to create example of how to add class conditionally in laravel blade.

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>Laravel Blade Conditional Class Example</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>Laravel Blade Conditional Class Example</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>Laravel Blade Conditional Class Example</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