Skip to content

Querying Users

Warden provides query scopes to filter users by their roles.

You can query your users by whether they have a given role:

$users = User::whereIs('admin')->get();

Pass in multiple roles to query for users that have any of the given roles:

$users = User::whereIs('superadmin', 'admin')->get();

To query for users who have all of the given roles, use the whereIsAll method:

$users = User::whereIsAll('sales', 'marketing')->get();

Query for users who don’t have specific roles:

$users = User::whereIsNot('banned')->get();

Get all administrators:

$admins = User::whereIs('admin')->get();

Get users who are either editors or moderators:

$staff = User::whereIs('editor', 'moderator')->get();

Get users who have both sales and marketing roles:

$salesMarketing = User::whereIsAll('sales', 'marketing')->get();

Combine with other query methods:

$activeAdmins = User::whereIs('admin')
->where('active', true)
->orderBy('name')
->get();

Get paginated list of editors:

$editors = User::whereIs('editor')->paginate(20);

Count users with a specific role:

$adminCount = User::whereIs('admin')->count();

Query roles directly:

use Cline\Warden\Database\Role;
$roles = Role::all();
$adminRole = Role::where('name', 'admin')->first();

Query abilities:

use Cline\Warden\Database\Ability;
$abilities = Ability::all();
$banAbility = Ability::where('name', 'ban-users')->first();

Get users for a specific role:

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

Get abilities for a role:

$role = Role::where('name', 'editor')->first();
$abilities = $role->abilities;