Checking whether a variable exists or not is an important step before printing its value in a view.
If you print an 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 Laravel 5.7, we can use the 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