Ternary Operator Laravel Blade Code Example
Aug 09, 2022 . Admin
Hello Friends,
In this tutorial we will go over the demonstration of Ternary Operator Laravel Blade Code Example. I’m going to show you about laravel ternary operator in blade. I explained simply about how to use ternary operator in laravel. step by step explain ternary operator in laravel blade. Here, Creating a basic example of if condition 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 LaravelLet 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-appUse 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>Ternary Operator Laravel Blade Code Example - Mywebtuts.com</title> </head> <body> <p>{{ $variable ?? "default" }}</p> </body> </html>Output:
defaultExample 2 :
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Ternary Operator Laravel Blade Code Example - Mywebtuts.com</title> </head> <body> <p>{{ Auth::check() ? 'Hi User' : 'Hi Guest' }}</p> </body> </html>Output:
Hi UserExample 3 :
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Ternary Operator Laravel Blade Code Example - Mywebtuts.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...