rockbuzz/lara-rbac

This package is abandoned and no longer maintained. The author suggests using the https://github.com/rockbuzz/lara-rbac package instead.

Role Based Access Control per resource

0.0.4 2020-12-04 18:07 UTC

This package is auto-updated.

Last update: 2021-06-29 09:50:11 UTC


README

Role Based Access Control per resource

Build Status

Requirements

PHP >=7.3

Install

$ composer require rockbuzz/lara-rbac
$ php artisan vendor:publish --provider="Rockbuzz\LaraRbac\ServiceProvider" --tag="migrations"
$ php artisan migrate

Add Rbac trait to your User model

use Rockbuzz\LaraRbac\Traits\HasRbac;
use Rockbuzz\LaraRbac\Contracts\HasRbac as RbacInterface;
	
class User extends Authenticatable implements RbacInterface
{
    use HasRbac;
    ...
	    
}

Usage

Roles

Create role

$adminRole = new \Rockbuzz\LaraRbac\Models\Role;
$adminRole->name = 'admin';
$adminRole->save();

$writerRole = new \Rockbuzz\LaraRbac\Models\Role;
$writerRole->name = 'writer';
$writerRole->save();

Assign role to user

$user = User::find(1);
$user->attachRole($adminRole, $resource);

or

$user->attachRole($adminRole->id, $resource);

or

$user->attachRole([$adminRole->id, $writerRole->id], $resource);

Sync roles to user

$user->syncRoles([$adminRole->id, $writerRole->id], $resource);

Revoke role from user

$user->detachRoles([$adminRole, $writerRole->id], $resource);

Permissions

Create permission

$postStore = new \Rockbuzz\LaraRbac\Models\Permission;
$postStore->name = 'post.store';
$postStore->save();

$postUpdate = new \Rockbuzz\LaraRbac\Models\Permission;
$postUpdate->name = 'post.update';
$postUpdate->save();

Assign permission to role

https://laravel.com/docs/6.x/eloquent-relationships

Assign permission to user

$user = User::find(1);
$user->attachPermission($postStore, $resource);

or

$user->attachPermission($postStore->id, $resource);

or

$user->attachPermission([$postStore->id, $postUpdate->id], $resource);

Sync permissions to user

$user->syncPermissions([$postStore->id, $postUpdate->id], $resource);

Revoke permission from user

$user->detachPermissions([$postStore->id, $postUpdate->id], $resource);

Check user roles/permissions

auth()->user()->hasRole('admin', $resource);
auth()->user()->hasRole('admin|writer', $resource);
auth()->user()->hasPermission('post.update', $resource);
auth()->user()->hasPermission('post.update|delete.post', $resource);

Blade directive

Check for role

@hasrole('admin', $resource)
    // ok
@else
    // no
@endrole

Check for permission

@haspermission('post.store|post.update', $resource)
    // ok
@else
    // no
@endpermission

License

The Lara RBAC is open-sourced software licensed under the MIT license.