Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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'; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...