9

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 Answer 1

25

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.