How to Use Ternary Operator in Laravel Blade?

Aug 09, 2022

.

Admin

How to Use Ternary Operator in Laravel Blade?

Hello Friends,

This example is focused on How to Use Ternary Operator in Laravel Blade?. if you want to see example of laravel ternary operator in blade then you are a right place. it's simple example of how to use ternary operator in laravel. you will learn ternary operator in laravel blade.

in this example, i am trying to implement a conditional operator on a value returned from controller to create some custom view. a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.

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

Use Ternary Operator in Blade File:

Example 1 :

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Use Ternary Operator in Laravel Blade - Nicesnippets.com</title>

</head>

<body>

<p>{{ $variable ?? "default" }}</p>

</body>

</html>

Output:

default

Example 2 :

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Use Ternary Operator in Laravel Blade - Nicesnippets.com</title>

</head>

<body>

<p>{{ Auth::check() ? 'Hi User' : 'Hi Guest' }}</p>

</body>

</html>

Output:

Hi User

Example 3 :

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Use Ternary Operator in Laravel Blade - Nicesnippets.com</title>

</head>

<body>

<p>{{ $user->is_active == 1 ? 'Active' : 'Inactive' }}</p>

</body>

</html>

Output:

Active

now it works...

I hope it can help you...

#Laravel