Check if variable exists with Laravel Blade directive

Checking whether a variable exists or not is an important step before printing its value in a view.

If you print a un-declared variable, Laravel will generate errors.

There are 4 approaches in Blade.

@isset Directive

    {{ $car_name}}

@empty Directive

    <p>Welcome, {{ $user }}</p>

Ternary Operator

Starting from Lravel 5.7, we can use ternary operator to check a variable’s existence. Both ?? and or operators are allowed.

//print price if it exists, otherwise print 0.00
{{ $price ?? '0.00' }}
{{ $price or '0.00' }}

if isset() Method

    {{ $client->name }}

Leave a Comment

Your email address will not be published. Required fields are marked *