PHP code example of huang-yi / laravel-rbac

1. Go to this page and download the library: Download huang-yi/laravel-rbac library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

huang-yi / laravel-rbac example snippets


namespace App;

use HuangYi\Rbac\Concerns\Authorizable;
use HuangYi\Rbac\Contracts\Authorizable as AuthorizableContract;

class User extends Authenticatable implement AuthorizableContract
{
    use Authorizable, Notifiable;
}

use HuangYi\Rbac\Permission;

Permission::make('edit post');

use HuangYi\Rbac\Role;

Permission::make('personnel manager');

$role->attachPermissions($permissions);

$role->detachPermissions($permissions);

$role->syncPermissions($permissions);

$user->attachRoles($roles);

$user->detachRoles($roles);

$user->syncRoles($roles);

$user->attachPermissions($permissions);

$user->detachPermissions($permissions);

$user->syncPermissions($permissions);

$user->hasRole('author');

$user->hasRoles(['author', 'personnel manager']);

$user->hasAnyRoles(['author', 'personnel manager']);

$user->hasPermission('create post');

$user->hasPermissions(['create post', 'edit post']);

$user->hasAnyPermissions(['create post', 'edit post']);

// this is similar to hasAnyPermissions
$user->can('edit post|edit post');

namespace App\Providers;

use HuangYi\Rbac\Rbac;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Rbac::checkSuperAdminUsing(function ($user) {
            return in_array($user->email, ['[email protected]']);
        });
    }
}

// role middleware
Route::get('admin/staffs', [StaffController::class, 'index'])->middleware('role:personnel manager|vice president');

// permission middleware
Route::post('post/{post}', [PostController::class, 'update'])->middleware('permission:create post|edit post');

// this is similar to 'permission' middleware
Route::post('post/{post}', [PostController::class, 'update'])->middleware('can:create post|edit post');
shell
php artisan vendor:publish --provider="HuangYi\Rbac\RbacServiceProvider"
shell
php artisan migrate