Skip to content
Advertisement

I want to show roles related to users in selection option using laravel

I am trying to show roles which is related to user but unfortunately userRoles are not showing related to user in selection option, please help me how can I match that thanks.

Note :- I am using spaite laravel permission docs

controller

public function edit(User $user)
    {

        $data = [

            'isEdit' => true,
            'user' => $user,
            'roles' => Role::where('guard_name', '=', 'web')->select(['id', 'name'])->get(),

            'userRole' => $user->getRoleNames(),                 
              // i am getting userRole in array related to user
             //  ['employe']

        ];
        // return $data['userRole'];
        return view('cms.user_management.add-user', $data);
    }

html view

                     <div class="col-md-6">
                            <div class="form-group">
                              <label>Role <span class="text-danger">*</span></label>
                                <select class="form-control" name="roles[]">
                                    <option selected="selected" disabled >please 
                                   select</option>
                                    @foreach ($roles as $item)
                                   <option value="{{ $item->name }}"{{ $userRole == 
                                $item->name ? ' selected' : '' }}>{{ $item->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <span class="text-danger">{{ $errors->first('roles') ?? null }} 
                           </span>
                          </div>

Advertisement

Answer

Try the following changes in your HTML If $userRole is array than check if $item->name exists in array, using in_array.

 'userRole' => $user->getRoleNames()->toArray(),

html view

{{ in_array($item->name, $userRole) ? 'selected' : '' }}


<div class="col-md-6">
     <div class="form-group">
          <label>Role<span class="text-danger">*</span></label>
              <select class="form-control" name="roles[]">
                  <option selected="selected" disabled>please select</option>
                       @foreach ($roles as $item)
                             <option value="{{ $item->name }}"{{ in_array($item->name,$userRole) ? 'selected' : '' }}>{{ $item->name }}</option>
                       @endforeach
               </select>
       </div>
   <span class="text-danger">{{ $errors->first('roles') ?? null }}</span>
</div>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement