The HasRoles trait
Add HasRoles to any authenticatable model. There is no $guard_name to set:
use Illuminate\Foundation\Auth\User as Authenticatable;
use RoundlyConsulting\Permissions\Concerns\HasRoles;
class User extends Authenticatable
{
use HasRoles;
}HasRoles already includes HasPermissions, so this one trait gives the model role assignment, direct permission grants and effective-permission resolution.
Relations
The trait adds two polymorphic relations. Every check is eager-load aware — it reads the loaded relation when present and lazy-loads otherwise:
$user->roles(); // MorphToMany<Role> — the relation
$user->roles; // Collection<Role> assigned to this model
$user->permissions(); // MorphToMany<Permission> — direct grants
$user->permissions; // Collection<Permission>, direct grants onlyWhat the trait adds
- assignRole(), removeRole(), syncRoles() — manage the model’s roles.
- givePermissionTo(), revokePermissionTo(), syncPermissions() — manage its direct grants.
- hasRole(), hasPermissionTo() — check access.
- getRoleNames(), getPermissionNames(), getDirectPermissions(), getAllPermissions() — read what the model holds.
- forgetAllAuthorization() — detach every role and direct permission, e.g. before deleting the model.
- role() — a query scope that filters models by role.
The write methods are sugar over Permissions::for($model) — they delegate to the same PermissionsManager, so a container override applies and Permissions::fake() records them. Reads stay on the model.
Beyond users
Any Eloquent model can hold roles and permissions — teams, organisations, API clients. Laravel’s Gate authorizes authenticatable users, so the can: integration applies to your user model; check other holders with hasRole() and hasPermissionTo():
use Illuminate\Database\Eloquent\Model;
use RoundlyConsulting\Permissions\Concerns\HasRoles;
class Team extends Model
{
use HasRoles;
}
$team->assignRole('enterprise');
$team->givePermissionTo('billing.invoices.export');
$team->hasRole('enterprise'); // true
$team->hasPermissionTo('billing.invoices.export'); // trueShow your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.