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

@isset($car_name)
    {{ $car_name}}
@endisset

@empty Directive

@if(empty($user))
    <p>Guest</p>
@else
    <p>Welcome, {{ $user }}</p>
@endif

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

@if(isset($client))
    {{ $client->name }}
@endif

Leave a Comment

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