Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all users with role in Laravel

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!

like image 911
jdfauw Avatar asked Mar 18 '14 17:03

jdfauw


3 Answers

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.

like image 93
duellsy Avatar answered Nov 17 '22 03:11

duellsy


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

$teachers = User::role('Teacher')->get();
like image 5
Quique Garcia Avatar answered Nov 17 '22 04:11

Quique Garcia


Try This.

Role::where('rolename', 'user')->first()->users()->get()
like image 3
Deepak singh Thakur Avatar answered Nov 17 '22 03:11

Deepak singh Thakur