Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for an easy way to skip undefined variables in blade template

Instead of constantly making an if statement to see if a variable is in the array, I would like a simpler solution. Does anyone know of one?

@if(isset($content->title))
    <h2>{{ $content->title }}</h2>
@endif

Or

{{ (isset($content-title)) ? "<h2>$content->title</h2>" : "" }}

Is in my opinion way too much coding. So I am hoping someone knows of a plugin that does something like:

{{ @$content->title }}

Thanx in advance

like image 700
Alvin Bakker Avatar asked Dec 24 '22 11:12

Alvin Bakker


1 Answers

Blade has a special or keyword for this:

<h2>{{ $content->title or '' }}</h2>

Read about it in the documentation, under the title Echoing Data If It Exists.


In newer versions of PHP, you can use the ?? operator for this:

<h2>{{ $content->title ?? '' }}</h2>
like image 114
Joseph Silber Avatar answered Dec 28 '22 08:12

Joseph Silber