PHP code example of shiwuhao / laravel-rbac

1. Go to this page and download the library: Download shiwuhao/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/ */

    

shiwuhao / laravel-rbac example snippets




namespace App\Models;

class Role extends \Shiwuhao\Rbac\Models\Role
{

}



namespace App\Models;

class Permission extends \Shiwuhao\Rbac\Models\Permission
{

}



namespace App\Models;

class Action extends \Shiwuhao\Rbac\Models\Action
{

}



namespace App\Models;

use Shiwuhao\Rbac\Models\Traits\UserTrait;

class User extends Authenticatable
{
    use UserTrait; // 添加这个trait到你的User模型中
}




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Shiwuhao\Rbac\Models\Traits\PermissibleTrait;

class Menu extends Model
{
    use PermissibleTrait;
}


$action = new App\Models\Action();
$action->name= 'user:index';
$action->label= '用户列表';
$action->method= 'get';
$action->uri= 'backend/users';
$action->save();

$role = new App\Models\Role();
$role->name= 'Administrator';
$role->label= '超级管理员';
$role->remark= '备注';
$role->save();

$role = App\Models\Role::find(1);

// 绑定权限
$role->permissions()->sync([1, 2, 3, 4]); // 同步
$role->permissions()->attach(5);// 附加
$role->permissions()->detach(2);// 分离

// 绑定用户
$role->users()->sync([1, 2, 3, 4]);// 同步
$role->users()->attach(5);// 附加
$role->users()->detach(5);// 分离

$user = App\Models\User::find(1);
$user->roles;

$user->roles()->sync([1, 2, 3, 4]);// 同步
$user->roles()->attach(5);// 附加
$user->roles()->detach(5);// 分离

$user->permissions;

$user->hasRole('admin');
$user->hasRole(['admin','test'],true);
$user->hasPermission('user:add');
$user->hasPermission($names = ['user:add','user:edit'],$checkColumn = 'name',$and = false);

protected $routeMiddleware = [
    'permission' => Shiwuhao\Rbac\Middleware\PermissionMiddleware,
];

Route::middleware('permission')->group(function () {
    Route::prefix('backend')->group(function () {
        Route::get('users', [UserController::class, 'index']);
    });
});
shell
php artisan vendor:publish
shell
php artisan migrate
shell
php artisan rbac:auto-generate-actions