Ternary in Laravel Blade

LaravelTernary OperatorBlade

Laravel Problem Overview


Looking for a ternary operator for blade templates

@if(Auth::check()) ? yes : no @endif

Can't seem to get it to work this works

@if(Auth::check()) yes @else no @endif

suppose there is not much in it for this example, just curious.

Laravel Solutions


Solution 1 - Laravel

You are free to use it with {{ }}.

{{ Auth::check() ? 'yes' : 'no' }}

Solution 2 - Laravel

This works:

{{ Auth::check() ? 'yes' : 'no' }}

Solution 3 - Laravel

I know this question was asked a while ago, but this may help somebody.

You can now do this in Laravel 5.

{{ $variable or "default" }}

Laravel 5 Blade Templates

Laravel 5.2 Blade Template

Solution 4 - Laravel

in addition, here is a nice shortcut ?:, if you you need to print some variable's value or if it's empty some default text

{{ $value ?: 'Default Value' }}

Solution 5 - Laravel

For Laravel 5 + php7, you should be using the null coalesce operator as explained in this Laravel News article, like so:

{{ $value ?? "Fallback" }}

> Before the null coalescing operator, Blade handled the same problem with the “or” operator, which allows a default value when the first value isn’t set, separated by an “or”.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeBlaireauView Question on Stackoverflow
Solution 1 - LaravelMarwellnView Answer on Stackoverflow
Solution 2 - LaravelLaurenceView Answer on Stackoverflow
Solution 3 - LaravelBryceView Answer on Stackoverflow
Solution 4 - LaravelvitrView Answer on Stackoverflow
Solution 5 - LaravelChadView Answer on Stackoverflow