7
votes

I got a many to many user and role structure

users
id
name

roles
id
name

role_user
user_id
role_id

Model

User.php

public function roles() {
    return $this->belongsToMany('Role');
}

Role.php

public function users() {
    return $this->belongsToMany('User');
}

There are two data admins and members in roles table, I would like to know to to filter users which role is admins.

1

1 Answers

21
votes

This should give you all users who are admins.

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

You can see more information on the has() method at http://laravel.com/docs/eloquent#querying-relations