role based access control for laravel framework
install via composer:
composer require aries/laravel-rbac
publish environment:
php artisan vendor:publish --provider='Aries\LaravelRbac\LaravelRbacServiceProvider'
enable package in .env
file:
RBAC_ENABLE=true
then run migration to create roles and abilitie table:
php artisan migrate
you need to extend your User
model from Aries\LaravelRbac\Models\User
like this:
<?php
namespace App/Models;
...
use Aries\LaravelRbac\Models\User as RbacUser;
...
class User extends RbacUser
{
...
you can create role for a user like this:
$user = App\Models\User::first();
$user->roles()->create([
'name' => 'role-name',
'label' => 'optional role label'
]);
also you can sync user roles with existing roles like this:
$user = App\Models\User::first();
$roles = Aries\LaravelRbac\Models\Role::all()->pluck('id')->toArray();
$user->roles()->attach($roles);
you can create an ability like this:
$ability = Aries\LaravelRbac\Models\Ability::create([
'name' => 'ability-name',
'label' => 'optional ability label'
]);
also you can create an ability throgh role model like this:
$role = Aries\LaravelRbac\Models\Role::first();
$role->abilities()->create([...]);
or you can assign many existing abilities to a role like this:
$abilities = Aries\LaravelRbac\Models\Ability::all()->pluck('id')->toArray();
$role = Aries\LaravelRbac\Models\Role::first();
$role->abilities()->attach($abilities);
this package defined Gate for each ability and you can use it in middlewares, controllers or views by default.
read official document for Gate and Policy.
also you can check a user has a role or ability throgh user model:
$user = App\Models\User::first();
$user->hasRole('role-name') # return bool
$user->hasAbility('ability-name') # return bool