Get all users with role in Laravel
Asked Answered
B

6

19

I'm working in this Laravel project which has this structure

users: id | first_name |...

roles: id | name

assigned_roles: id | user_id | role_id

I think this is quite obvious :p

User model

class User extends ConfideUser {
use HasRole;

public function Roles(){
    return $this->belongsToMany('Role','assigned_roles');
}

Role model

class Role extends EntrustRole
{
public function Users()
{
    return $this->belongsToMany('User','assigned_roles');
}


} 

I'm looking for a way to get all users with a specified role in this case 'Teacher'. I've tried this:

$students = User::with(array('Roles' => function($query) {
        $query->where('name','Teacher');
    }))
    ->get();
    return $students;

but this always returns an array of all users.

would anyone know why that's so? Thanks!

Besprent answered 18/3, 2014 at 17:57 Comment(0)
K
47

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.

Kiaochow answered 18/3, 2014 at 21:41 Comment(2)
Are there other ways to retrieve this, because this might have performance issues. Should we consider using index on user_id on role?Primipara
You could use this package which is very nice, github.com/mpyw/eloquent-has-by-non-dependent-subqueryHeirship
N
8

If you are using spatie/laravel-permission or backpack/permissionmanager you can simply do:

$teachers = User::role('Teacher')->get();
Naples answered 2/12, 2021 at 4:12 Comment(0)
S
5

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();
Systaltic answered 1/6, 2020 at 14:59 Comment(0)
W
3

Try This.

Role::where('rolename', 'user')->first()->users()->get()
Westnorthwest answered 26/5, 2020 at 7:24 Comment(0)
L
0

If You Are using laravel-permission package then,

In Controller,

$rolesWithUserCount = Role::withCount('users')->get();

In Blade File,

@foreach ($rolesWithUserCount as $item)
          {{ $item->name }}
          {{$item->users_count }}
@endforeach

OutPut:

Role1 Role1Count 
Role2 Role2Count
 ....

For More: VISIT: https://laravel.com/docs/7.x/eloquent-relationships#counting-related-models

Lekishalela answered 3/9, 2020 at 13:47 Comment(0)
C
0

This would work exactly as intended:

$users = User::whereHas('roles' => function($q){$q->where('name', 'Teacher');})->get();
Casa answered 27/9, 2023 at 16:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.