Skip to content

Commit

Permalink
Merge pull request Zizaco#812 from yamenarahman/master
Browse files Browse the repository at this point in the history
Adding scopeWithRole($name) to filter users according to their role.
  • Loading branch information
Zizaco authored Nov 13, 2017
2 parents a76c21c + 1e60b43 commit 05b2542
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ class User extends Eloquent
}
```

This will enable the relation with `Role` and add the following methods `roles()`, `hasRole($name)`, `can($permission)`, and `ability($roles, $permissions, $options)` within your `User` model.
This will enable the relation with `Role` and add the following methods `roles()`, `hasRole($name)`, `withRole($name)`, `can($permission)`, and `ability($roles, $permissions, $options)` within your `User` model.

Don't forget to dump composer autoload

Expand Down Expand Up @@ -307,6 +307,13 @@ $user->can("admin.*"); // true
$user->can("*_users"); // true
```

To filter users according a specific role, you may use withRole() scope, for example to retrieve all admins:
```
$admins = User::withRole('admin')->get();
// or maybe with a relationsship
$company->users()->withRole('admin')->get();
```


#### User ability

Expand Down
14 changes: 14 additions & 0 deletions src/Entrust/Traits/EntrustUserTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -304,4 +304,18 @@ public function detachRoles($roles=null)
}
}

/**
*Filtering users according to their role
*
*@param string $role
*@return users collection
*/
public function scopeWithRole($query, $role)
{
return $query->whereHas('roles', function ($query) use ($role)
{
$query->where('name', $role);
});
}

}

0 comments on commit 05b2542

Please sign in to comment.