Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo a default value if value not set blade

I would like to know what would be the best way to display a default value if the given value is not set. I have the following in a blade file (I can not guaranty that the key is set, it depends on a multitude of factors).

{{ $foo['bar'] }} 

I would know if the following is the best way to go about it,

{{ (isset($foo['bar']) ? $foo['bar'] : 'baz' }} 

or is there a better way to do this?

Thanks :)

like image 909
paquettg Avatar asked Aug 02 '13 18:08

paquettg


People also ask

How do you declare a variable with default value?

To provide a default value for a variable, include a DEFAULT clause. The value can be specified as an expression; it need not be a constant. If the DEFAULT clause is missing, the initial value is NULL. When a variable is first declared, its value is set to NULL.

What is default var value?

Variables of any "Object" type (which includes all the classes you will write) have a default value of null.


1 Answers

Use php's null coalesce operator:

{{ $variable ?? "Default Message" }} 

Removed as of Laravel 5.7

With Laravel 4.1-5.6 you could simply do it like this:

{{ $variable or "Default Message" }} 

It's the same as:

echo isset($variable) ? $variable : 'Default Message';  
like image 105
Jazerix Avatar answered Sep 21 '22 09:09

Jazerix