laravellaravel-permission

list users by a specific role with laravel\spatie


I want to list in a <select> all users with specific role doctor, i'm using laravel spatie library

<label for="select_doctor">{{__("Select doctor") }}</label>
<select name="select_doctor" id="select_doctor" class="form-control">
  <option value="" selected disabled>----- * ----</option>

  @foreach (App\User::all()->hasRole('doctor') as $doctor)
    <option value="">{{ __($doctor->person->name) }}</option>
  @endforeach

</select>

But I get this error Method Illuminate\Database\Eloquent\Collection::hasRole does not exist


Solution

  • As specified in their docs, you can simply use User::role('role_name')->get() to get all users with the specific role.

    @foreach (App\User::role('doctor')->get() as $doctor)
      <option value="">{{ __($doctor->person->name) }}</option>
    @endforeach
    

    As a side note, you should do such condition checkings from your controller itself and pass the $doctors list to your blade