Get all users with role in Laravel Get all users with role in Laravel php php

Get all users with role in Laravel


What you're currently asking laravel for in your $students query, is 'give me all the students, and for each student get me all of their roles if the role is teacher'

Try using the whereHas

$students = User::whereHas(    'roles', function($q){        $q->where('name', 'Teacher');    })->get();

This should get you the users, but only where they have a role where the name is teacher.


Try This.

Role::where('rolename', 'user')->first()->users()->get()


In case you want to get all users with a list of potentials roles:

$authorizedRoles = ['Teacher', 'Professor', 'Super professor'];$users = User::whereHas('roles', static function ($query) use ($authorizedRoles) {                    return $query->whereIn('name', $authorizedRoles);                })->get();