Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get a collection of users in this role? #44

Closed
bobrovskikh opened this issue Oct 24, 2016 · 2 comments
Closed

How to get a collection of users in this role? #44

bobrovskikh opened this issue Oct 24, 2016 · 2 comments

Comments

@bobrovskikh
Copy link

Hello!

How to get a collection of users in this role?

Thank you

@KKSzymanowski
Copy link
Collaborator

KKSzymanowski commented Oct 24, 2016

As far as I know this has not been explained in the documentation, but it's fairly simple.

The User - Role relationship is a ManyToMany type, which means the User has many Roles and a Role is(or really can be) assigned to many Users.
In this case, as stated in the official framework documentation, we use a following relationship declaration:

public function posts()
{
    return $this->belongsToMany(Post::class);
}

Our case is exactly the same, meaning:

$user = User::first();

$roles = $user->roles; // Get all user roles.
// or
$roles = $user->roles()->get();

and

$role = Role::first();

$users = $role->users; // Get all users with this role assigned to them
// or
$users = $role->users()->get();

I hope this explains it for you.

By the way, this is an open source project, so you are more than engouraged to take a look at the package files.
The Role model uses Laratrust/Traits/LaratrustRoleTrait, and in this trait definition you'll find the relationship declaration.
It applies user configuration to be more flexible, but by default it would behave something like following:

public function users()
{
    return $this->belongsToMany(
        App\User::class,
        'role_user',
        'role_id',
        'user_id'
    );
}

which is just an explicit way of saying

public function users()
{
    return $this->belongsToMany(App\User::class);
}

As you can see there's not much magic going on.

@bobrovskikh
Copy link
Author

Thank you! Working!

$role = Role::where('name','=','administrator')->first();
$users = $role->users;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants