简体   繁体   中英

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)

{{ $usersType or '' }} is working fine. The problem here is your foreach loop:

@foreach( $usersType as $type )
    <input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span> &nbsp; 
@endforeach

I suggest you put this in an @if() :

@if(isset($usersType))
    @foreach( $usersType as $type )
        <input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span> &nbsp; 
    @endforeach
@endif

You can also use @forelse. Simple and easy.

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

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

{{ $usersType or '' }}  ❎
{{ $usersType ?? '' }} ✅

如果要回显,请使用 3 个花括号

{{{ $usersType or '' }}}

您可以轻松使用三元运算符:

{{ $usersType ? $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
@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

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

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

After new update in php

// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

Check the ref: https://laravel-news.com/blade-templates-null-coalesce-operator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM