Search code examples
phplaravelnull-coalescing-operator

Laravel 6 null coalescing operator gives Undefined variable: user when calling a method on it?


I'm trying to get this working.

<option value="{{$role->id}}" {{ (collect(old('userrole') ?? $user->roles()->pluck('id')->implode(", ") ?? '')->contains($role->id)) ? 'selected':'' }}>{{$role->name}}</option>

For some reason it won't work. It gives back the error: Undefined variable: user.

Any help?


Solution

  • The null-coalescing operator ?? will check if the final result is null or not - it will not take into consideration any variables that may be undeclared to obtain that result.

    You can therefor use a ternary operator to see if the $roles value is set or not for that expression.

    {{ (collect(
               old('userrole') 
                 ?? (isset($user) 
                         ? $user->roles()->pluck('id')->implode(", ") 
                         : ''
                     )
                )->contains($role->id)) 
                 ? 'selected'
                 : '' }}
    
    

    The old() helper also takes a second parameter, as "default" should the value not exist, which you can use. And since you're looking for a single value, the usage of a ternary operator to output selected can be replaced by a blade @if block.

    <option value="{{$role->id}}" 
        @if (collect(old('userrole', (isset($user) ? $user->roles()->pluck('id')->implode(", ") : ''))->contains($role->id)))
            selected
        @endif 
    >{{$role->name}}</option>
    

    You can also reduce som cluttering in the code by using contains() on the object itself (without having to pluck() the id`).

    <option value="{{ $role->id }}" 
        @if (collect(old('userrole', (isset($user) ? $user->roles())->contains($role->id)))
            selected
        @endif 
    >{{ $role->name }}</option>