How to Use Ternary Operator in Blade Templates

Let’s quickly look at how we can use the ternary operator in Blade templates.

Here we have a simple good old if/else statement.

If the login route exists, display ‘Yes’; if it doesn’t, display ‘No’.

There is nothing functionally wrong with this if/else code.

It’s just quite verbose and consumes more space for such a simple expression.

We can rewrite this using the ternary operator.

 

Ternary operator in a nutshell:

Make sure that the expression is between the brackets, otherwise, the engine will not understand the code.


Luckily, Blade does not restrict us from using PHP’s syntax.

That means we are free to use other operators as well such as:

  • Shorthand Ternary Operator: $var ?: 'John'
  • Null Coalescing Operator: $nullVal ?? 'John'
  • Null Coalescing Assignment Operator: $var ??= 'John'

These operators are syntax sugar only and do not provide meaningful performance differences compared to the old if/else statement.

Happy coding 😊


Let me know what you think about this article through comments below, or on Twitter at @pelu_carol.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.

 

You may also like...