Inside this article we will see the concept i.e Laravel 9 How To Use Ternary Operator in Blade Templates. Article contains the classified information about usage of ternary operator in blade templates.
The ternary operator is a conditional operator that decreases the length of code while performing comparisons and conditionals. This method is an alternative for using if-else and nested if-else statements.
Syntax #1 (Ternary Operator)
(Condition) ? (Statement1) : (Statement2);
- Condition: It is the expression to be evaluated which returns a boolean value.
- Statement 1: It is the statement, executed if the condition results in a true state.
- Statement 2: It is the statement, executed if the condition results in a false state.
Syntax #2 (NULL Coalescing Operator)
(Variable) ?? (Default Value);
If you have variable value then it will be printed else default value will be printed.
Learn More –
- Laravel 9 How To Generate UUID in Application Tutorial
- Laravel 9 How to Select Specific Columns in Eloquent Model
- Laravel 9 How To Get All Models From Application Tutorial
- Laravel 9 How to Make Hash Password Tutorial
Let’s get started.
Laravel Installation
Open terminal and run this command to create a laravel project.
composer create-project laravel/laravel myblog
It will create a project folder with name myblog inside your local system.
To start the development server of laravel –
php artisan serve
URL: http://127.0.0.1:8000
Assuming laravel already installed inside your system.
Example #1: NULL Coalescing Operator
Let’s say you have this blade template file and you can use the NULL Coalescing Operator like this way:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel 9 How To Use Ternary Operator in Blade Templates</title> </head> <body> <p>{{ $variable ?? "This is a default value" }}</p> </body> </html>
Concept
{{ $variable ?? "This is a default value" }}
Output
This is a default value
Example #2: Usage of Ternary Operator
Let’s say you have this blade template file and you can use the Ternary Operator like this way:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel 9 How To Use Ternary Operator in Blade Templates</title> </head> <body> <p>{{ Auth::check() ? 'Hi User' : 'Hi Guest' }}</p> </body> </html>
Concept
{{ Auth::check() ? 'Hi User' : 'Hi Guest' }}
Output
Hi User
We hope this article helped you to learn Laravel 9 How To Use Ternary Operator in Blade Templates in a very detailed way.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.