Camron Cade

Artisan web development, mostly using Laravel.

Blade shortcut for echoing variables that may not be set

Laravel is one of those frameworks that has hidden tricks that are a delight to stumble across.

This is one of them.

In your blade templates, you've probably done something like this:

{{ $day->common_sense }}

This is all fine and dandy, but what if the day doesn't exist? What if the day doesn't have any common sense?

If the attribute common_sense does not exist, an exception will be thrown and your entire app falls apart.

(The message you get might be something like this: Undefined property: stdClass::$common_sense")

You might solve the issue by first checking like so:

{{ isset($user->common_sense) ? $user->common_sense : '' }}

Here's where Laravel has already anticipated you trying this. Built into blade is a neat feature that is equivalent to the code above.

{{ $user->common_sense or '' }}