PHP code example of phpexperts / laravel-rbac
1. Go to this page and download the library: Download phpexperts/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/ */
phpexperts / laravel-rbac example snippets
PHPExperts\LaravelRBAC\RbacServiceProvider::class,
protected $routeMiddleware = [
...
'rbac' => '\PHPExperts\LaravelRBAC\Middleware\Rbac::class'
];
use PHPExperts\LaravelRBAC\Traits\Rbac;
class User extends Authenticatable
{
use HasRoles;
...
}
$adminRole = new Role;
$adminRole->name = 'Administrator';
$adminRole->slug = 'administrator';
$adminRole->description = 'System Administrator';
$adminRole->save();
$editorRole = new Role;
$editorRole->name = 'Editor';
$editorRole->slug = 'editor';
$editorRole->description = 'Editor';
$editorRole->save();
$user = User::find(1);
$user->roles()->attach($adminRole->id);
$user->roles()->attach([$adminRole->id, $editorRole->id]);
$user->roles()->detach($adminRole->id);
$user->roles()->detach([$adminRole->id, $editorRole->id]);
$user->roles()->sync([$editorRole->id]);
$createUser = new Permission;
$createUser->name = 'Create user';
$createUser->slug = 'user.create';
$createUser->description = 'Permission to create user';
$createUser->save();
$updateUser = new Permission;
$updateUser->name = 'Update user';
$updateUser->slug = 'user.update';
$updateUser->description = 'Permission to update user';
$updateUser->save();
$adminRole = Role::find(1);
$adminRole->permissions()->attach($createUser->id);
$adminRole->permissions()->attach([$createUser->id, $updateUser->id]);
$adminRole->permissions()->detach($createUser->id);
$adminRole->permissions()->detach([$createUser->id, $updateUser->id]);
$adminRole->permissions()->sync([$updateUser->id]);
$isAdmin = Auth::user()->hasRole('administrator'); // pass role slug as parameter
$isAdminOrEditor = Auth::user()->hasRole('administrator|editor'); // using OR operator
$canUpdateUser = Auth::user()->canDo('update.user'); // pass permission slug as parameter
$canUpdateOrCreateUser = Auth::user()->canDo('update.user|create.user'); // using OR operator
Route::get('/backend', [
'uses' => 'BackendController@index',
'middleware' => ['auth', 'rbac:is,administrator']
]);
Route::get('/backend', [
'uses' => 'BackendController@index',
'middleware' => ['auth', 'rbac:is,administrator|editor']
]);
Route::get('/dashboard', [
'uses' => 'DashboardController@index',
'middleware' => ['auth', 'rbac:can,view.dashboard']
]);
Route::get('/dashboard', [
'uses' => 'DashboardController@index',
'middleware' => ['auth', 'rbac:can,view.dashboard|view.statistics']
]);
$ php artisan migrate