laravel 权限管理 常用命令
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
$role = Role::create(['name' => 'writer']);
$permission = Permission::create(['name' => 'edit articles']);
$permissions = $user->permissions; //分配给用户的所有权限的列表
$permissions = $user->getAllPermissions(); //获取用户通过角色继承的所有权限
$roles = $user->getRoleNames(); //获取所有已定义的角色的集合
$users = User::role('writer')->get(); //仅返回具有“作者”角色的用户
$users = User::permission('edit articles')->get(); //仅返回具有“编辑文章”权限的用户
给权限:
$user->givePermissionTo('edit articles');
$user->givePermissionTo('edit articles', 'delete articles'); //一次赋予多个权限
$user->givePermissionTo(['edit articles', 'delete articles']) //一次赋予多个权限的数组
撤消:
$user->revokePermissionTo('edit articles');
$user->syncPermissions(['edit articles', 'delete articles']);//一次性撤消 并添加新的权限
$user->hasPermissionTo('edit articles'); //是否有权限
$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']); //或者用户是否有多个权限
分配角色:
$user->assignRole('writer');
$user->assignRole('writer', 'admin'); // 一次分配多个角色
$user->assignRole(['writer', 'admin']); // 一次分配一个角色数组
$user->removeRole('writer');
$user->syncRoles(['writer', 'admin']); //所有当前角色将从用户中删除,并由给定的数组替换
$user ->getDirectPermissions() //或$user -> permissions; //直接权限
$user ->getPermissionsViaRoles(); //从用户角色继承的权限
$user ->getAllPermissions(); //所有适用于用户的权限(继承和直接)