First of all, amazing package. Super simple to use!
I guess in theory you can hit the Roles table and grab all users where role = x
But it would be nice to have a function that does something like, User::whereRole('trial user')->all() for example.
I was just about to post about how my theory failed and had another idea. So for people looking to get around the same issue, with the feature not implemented, here's what you can do:
$role = Role::where('name', 'admin')->first();
$usersOfRole = $role->users()->get();
Eloquent has you covered with the whereHas method. It can be used to query relations of a model.
This is how you use it:
User::whereHas('role', function(Builder $query) {
return $query->name === 'trial user';
});
Disclaimer: untested code 馃槃 If it doesn't work, just search the Laravel docs for whereHas.
Just to leave a trace, if anyone is looking for this, I couldn't make the code above from @freekmurze work, so I went on and checked the Laravel docs ;-)
This would work:
User::whereHas('roles', function ($query) {
return $query->where('name', 'name-of-role');
});
What I changed was "role" to "roles" as the relationship on the hasRoles trait uses the word in plural, and I couldn't query the "name" field directly, had to search for it.
My use case was that I needed to find the person holding the role "owner" on a certain model, so I went on and created an accessor on said model:
public function getOwnerAttribute()
{
return $this->users()->whereHas('roles', function ($query) {
return $query->where('name', 'owner');
})->first();
}
So also, thanks Freek, I actually never had a use case for whereHas before, now I'll probably use it everywhere I can! :D
User::role('trial user')->get();
How do I make this work with or? This does not work User::role('admin|moderator')->get();
I figured out the answer to my own question ... here is what I did in case anybody else needs it.
$operator_admins = User::role('operator_admin')->orderBy('name')->pluck('name', 'id');
$operator_accountants = User::role('operator_accountant')->orderBy('name')->pluck('name', 'id');
$operator_technicians = User::role('operator_technician')->orderBy('name')->pluck('name', 'id');
$manager_select = $operator_admins->union($operator_accountants)->union($operator_technicians);
You could try User::hasAnyRole(['operator_admin','operator_accountant','operator_technician'])->get();
@dweb-x I tried your code - throws error Non-static method App\User::hasAnyRole() should not be called statically
The User::role() scope allows you to pass a role name as a string, or an array of role-name-strings, or a collection of role objects.
Thus User::role(['role1', 'role2', 'role3'])->get() should work, as would User::role($collectionOfRoleObjects)->get()
@drbyte yessir ... that worked
$manager_select = User::role(['operator_admin','operator_accountant','operator_technician'])->orderBy('name')->pluck('name', 'id');
Most helpful comment
User::role('trial user')->get();