ENTRUST 在项目中的配置就不说了,直接说使用
为用户 增加/删除用户组(role_user)
//用户
$user=Auth::user();
//用户组(以自己已有用户组实际为主)
$admin = Role::query()->where('name', 'super_admin')->first();
//添加用户到用户组
$user->attachRole($admin);
//从用户组删除用户
$user->detachRole($admin);
//清空用户组数据
$user->detachRoles()
为用户组 增加/删除权限(permission_role)
//权限
$permission_super_admin = Permission::query()->where('name', 'super_admin')->first();
//增加权限
$admin->attachPermission($permission_super_admin);
//删除权限
$admin->detachPermission($permission_super_admin);
//detachPermissions() 参数 array permission_id(本人只测试过permission_id)删除多个权限
$admin->detachPermissions(array $array());
注意:detachPermissions()如果参数为空会报错和detachRoles()不一样
ability
$options = array(
'validate_all' => false,默认值false,此时只要有一个true,就会返回true
'return_type' => 'both'
);
$res= $user->ability('super_admin', 'admin,user', $options);
dd($res);
输出:
array:2
0 => true
1 => array:2
["roles" => array:1
["super_admin" => true ]
"permissions" => array:2
["admin" => true "user" => false]
]]
Middleware
//用户组user才能访问
Route::group(['middleware'=>'role:user'],function() {
Route::get('test','DashboardsController@test');
});
//或者具有admin权限的能访问
Route::group(['middleware'=>'permission:admin'],function() {
Route::get('test','DashboardsController@test');
});
如果没有权限访问,会返回http 403
Checking for Roles & Permissions
//检查用户组
$user->hasRole('admin');
$user->can('create-post');