[php] Blade if(isset) is not working Laravel

Hi I am trying to check the variable is already set or not using blade version. But the raw php is working but the blade version is not. Any help?

controller:

public function viewRegistrationForm()
{
    $usersType = UsersType::all();
    return View::make('search')->with('usersType',$usersType);
}

view:

{{ $usersType or '' }}

it shows the error :

Undefined variable: usersType (View: C:\xampp\htdocs\clubhub\app\views\search.blade.php)

This question is related to php laravel

The answer is


@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

I solved this using the optional() helper. Using the example here it would be:

{{ optional($usersType) }}

A more complicated example would be if, like me, say you are trying to access a property of a null object (ie. $users->type) in a view that is using old() helper.

value="{{ old('type', optional($users)->type }}"

Important to note that the brackets go around the object variable and not the whole thing if trying to access a property of the object.

https://laravel.com/docs/5.8/helpers#method-optional


@isset($usersType)
  // $usersType is defined and is not null...
@endisset

For a detailed explanation refer documentation:

In addition to the conditional directives already discussed, the @isset and @empty directives may be used as convenient shortcuts for their respective PHP functions


You can use the ternary operator easily:

{{ $usersType ? $usersType : '' }}

Use 3 curly braces if you want to echo

{{{ $usersType or '' }}}

Use ?? , 'or' not supported in updated version.

{{ $usersType or '' }}  ?
{{ $usersType ?? '' }} ?

Use ?? instead or {{ $usersType ?? '' }}


On Controller

$data = ModelName::select('name')->get()->toArray();
return view('viewtemplatename')->with('yourVariableName', $data);

On Blade file

@if(isset($yourVariableName))
//do you work here
@endif