Basic Usage
Roles & Permissions
Create roles and permissions and assign them to models.
Creating roles and permissions
Roles and permissions are plain Lucid models:
import Permission from '#models/permission'
import Role from '#models/role'
const role = await Role.create({ name: 'writer' })
const permission = await Permission.create({ name: 'edit articles' })
// create only if it does not exist
await Role.findOrCreate({ name: 'editor' })
Lookups:
await Role.findByName('writer')
await Role.findById(1)
Both throw a 404 error if nothing is found.
Assigning permissions
Methods on User (or any model with HasPermissions/HasAuthorizable) and on Role are the same. They accept names, model instances, or several at once:
await role.givePermissionTo('edit articles')
await role.givePermissionTo('edit articles', 'delete articles')
await user.givePermissionTo('edit articles')
await user.revokePermissionTo('edit articles')
// replace everything
await role.syncPermissions('edit articles', 'publish articles')
Assigning roles
await user.assignRole('writer')
await user.assignRole('writer', 'admin')
await user.revokeRole('writer')
// replace all roles
await user.syncRoles('admin', 'writer')
Guards
Roles and permissions belong to a guard (guard_name, defaults to defaultGuard). The same name may exist in different guards:
await Role.findOrCreate({ name: 'admin', guardName: 'api' })
await user.hasRole('admin', 'api')
await user.hasPermissionTo('edit articles', 'api')
Relations
Both roles and permissions are regular manyToMany relations on the model:
await user.load('roles')
await user.load('permissions')
await role.load('permissions')
Models that have a role or permission
const users = await role.modelsFor(User) // by model class
const same = await role.modelsFor('user') // by morph alias
