小贴士
1. laravel和laravel-permission的版本需要匹配,过高的laravel-permission版本可能不适用于低版本laravel
2. laravel-permission会在项目config文件夹下创建名为permission.php的配置文件,如果config文件夹下本来就存在同名文件需要移除或重命名旧文件
3.使用该扩展包的模型中不能存在名为permissions和roles字段,否则会使得其产生冲突并导致功能失效甚至报错
安装
1. 安装包文件
composer require spatie/laravel-permission
2. 在config/app.php文件的providers中添加
'providers' => [
// ...
Spatie\Permission\PermissionServiceProvider::class,
];
3. 发布迁移文件,并在config文件夹下生成permission.php
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
tips: 如果config文件夹下本来就存在permission.php文件需要移除或重命名该文件
4. 如果在本地缓存配置,需要用以下命令清除缓存:
php artisan optimize:clear
# or
php artisan config:clear
5. 执行迁移文件,生成数据表
php artisan migrate
使用
将名为Spatie\Permission\Traits\HasRoles的trait加入到需要使用权限的模型
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable {
use HasRoles;
// ...
}
1. 新增角色/权限
$role = Role::create(['name' => 'writer']);
$permission = Permission::create(['name' => 'edit articles']);
2. 权限--角色
// 单权限
$role->givePermissionTo($permission);
$permission->assignRole($role);
// 多个权限
$role->syncPermissions($permissions);
$permission->syncRoles($roles);
// 取消权限授予角色
$role->revokePermissionTo($permission);
$permission->removeRole($role);
3. 其他相关查询
// get a list of all permissions directly assigned to the user
$permissionNames = $user->getPermissionNames(); // collection of name strings
$permissions = $user->permissions; // collection of permission objects
// get all permissions for the user,either directly, or from roles, or from both
$permissions = $user->getDirectPermissions();
$permissions = $user->getPermissionsViaRoles();
$permissions = $user->getAllPermissions();
// get the names of the user's roles
$roles = $user->getRoleNames(); // Returns a collection
4. 使用HasRoles trait的模型,被赋予了名为role和permission的scope方法
$users = User::role('writer')->get(); // Returns only users with the role 'writer'
$users = User::permission('edit articles')->get(); // Returns only users with the permission 'edit articles' (inherited or directly)
5.由于Role和Permission模型继承了Eloquent,可以Eloquent相关方法属性
$all_users_with_all_their_roles = User::with('roles')->get();
$all_users_with_all_direct_permissions = User::with('permissions')->get();
$all_roles_in_database = Role::all()->pluck('name');
$users_without_any_roles = User::doesntHave('roles')->get();
$all_roles_except_a_and_b = Role::whereNotIn('name', ['role A','role B'])->get();
6. 权限--用户
// 赋予权限
$user->givePermissionTo('edit articles');
$user->givePermissionTo('edit articles', 'delete articles');
$user->givePermissionTo(['edit articles', 'delete articles']);
// 收回权限
$user->revokePermissionTo('edit articles');
// 检测是否具有权限
$user->hasPermissionTo('edit articles');
$user->can('edit articles'); // laravel 默认方法
// 是否具有其中任意权限
$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);
// 是否拥有全部权限
$user->hasAllPermissions(['edit articles', 'publish articles', 'unpublish articles']);
$user->hasDirectPermission('edit articles');
$user->hasAllDirectPermissions(['edit articles', 'delete articles']);
$user->hasAnyDirectPermission(['create articles', 'delete articles']);
// 返回通过赋予权限获取的权限
$user->getDirectPermissions(); // Or $user->permissions;
// 仅返回通过角色获取的权限
$user->getPermissionsViaRoles();
// 所有权限(直接赋予或角色赋予)
$user->getAllPermissions();
7. 角色--用户
// 授予单个角色
$user->assignRole('writer');
// 授予多个角色
$user->assignRole('writer', 'admin');
$user->assignRole(['writer', 'admin']);
// 收回授予角色
$user->removeRole('writer');
// All current roles will be removed from the user and replaced by the array given
// 收回当前角色并授予新角色
$user->syncRoles(['writer', 'admin']);
// 是否具有指定角色
$user->hasRole('writer');
// 是否具有至少其中一个角色
$user->hasRole(['editor', 'moderator']);
$user->hasAnyRole(['writer', 'reader']);
$user->hasAnyRole('writer', 'reader');
// 是否具有所有角色
$user->hasAllRoles(Role::all());
8. 角色--权限
$role->givePermissionTo('edit articles');
$role->hasPermissionTo('edit articles');
$role->revokePermissionTo('edit articles');
中间件 Middleware
1. 注册
要想使用该中间件,首先需要在app/Http/Kernel.php文件中注册
protected $routeMiddleware = [
// ...
'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middlewares\RoleOrPermissionMiddleware::class,
];
2. 使用
1) 路由中
Route::group(['middleware' => ['role:super-admin']], function(){
//
});
Route::group(['middleware' => ['permission:publish articles']], function(){
//
});
Route::group(['middleware' => ['role:super-admin','permission:publish articles']], function(){
//
});
Route::group(['middleware' => ['role_or_permission:super-admin|edit articles']], function(){
//
});
Route::group(['middleware' => ['role_or_permission:publish articles']], function(){
//
});
// 多个权限采用管道(pipe |)特性
Route::group(['middleware' => ['role:super-admin|writer']], function(){
//
});
Route::group(['middleware' => ['permission:publish articles|edit articles']], function(){
//
});
Route::group(['middleware' => ['role_or_permission:super-admin|edit articles']], function(){
//
});
2) 构造函数中
publicfunction__construct()
{
$this->middleware(['role:super-admin','permission:publish articles|edit articles']);
}
publicfunction__construct()
{
$this->middleware(['role_or_permission:super-admin|edit articles']);
}
artisan Commands
通过artisan 命令操作权限和角色
php artisan permission:create-role writer
php artisan permission:create-permission "edit articles"
// 带有guard name的新建
php artisan permission:create-role writer web
// 创建角色并赋予权限
php artisan permission:create-role writer web "create articles|edit articles"
// 按照guard name分别展示其角色和权限表
php artisan permission:show