Laravel Permission 中文文档

https://packagist.org/packages/spatie/laravel-permission

简易说明

创建一个角色

use Spatie\Permission\Models\Role;

$role = Role::create(['name' => 'writer']);

创建一个规则

use Spatie\Permission\Models\Permission;
$permission = Permission::create(['name' => 'edit articles']);

分配

给角色配置规则权限

$role->givePermissionTo($permission);//单个

给规则分配角色

$permission->assignRole($role);

批量分配

//删除所有当前权限并设置给定权限。
$role->syncPermissions($permissions);
//规则同步到角色
$permission->syncRoles($roles);

移除

角色删除规则

$role->revokePermissionTo($permission);

规则删除角色

$permission->removeRole($role);

用户模型

用户模型获得所有规则列表

$permissions = $user->permissions;

用户模型通过角色来获得规则

$permissions = $user->getPermissionsViaRoles();

获得所有角色列表

$roles = $user->getRoleNames(); // Returns a collection

给用户分配规则

$user->givePermissionTo('edit articles');
$user->givePermissionTo('edit articles', 'delete articles');//多个
$user->givePermissionTo('edit articles', 'delete articles');//数组形式

给用户分配角色

$user->assignRole('writer', 'admin');//多个
// or as an array
$user->assignRole(['writer', 'admin']);//数组

HasRoles trait类

获得某个角色的所有用户列表

$users = User::role('writer')->get(); // Returns only users with the role 'writer'

这个role可以接受字符串,模型,集合对象

判断用户是否拥有这个规则

$user->hasPermissionTo('edit articles');

或支持ID值

$user->hasPermissionTo('1');
$user->hasPermissionTo(Permission::find(1)->id);
$user->hasPermissionTo($somePermission->id);

判断用户是否拥有以下的任何一个权限

$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);

通过permission id

$user->hasAnyPermission(['edit articles', 1, 5]);

判断用户是否拥有以下的所有权限

$user->hasAnyPermissions(['edit articles', 'publish articles', 'unpublish articles']);

使用can

是否拥有edit articles权限

$user->can('edit articles');

角色

移除要替换的所有角色,并用新的替换

$user->syncRoles(['writer', 'admin']);

判断用户使用拥有以下任意一个的用户角色

$user->hasAnyRole(Role::all());

判断用户使用拥有以下所有的用户角色

$user->hasAnyRoles(Role::all());

用户获得规则

所有权限列表

$user->getDirectPermissions()

通过角色所有规则

$user->getPermissionsViaRoles();

上面2种方式

$user->getAllPermissions();

视图

角色

@role('writer')
    I am a writer!
@else
    I am not a writer...
@endrole
//等价
@hasrole('writer')
    I am a writer!
@else
    I am not a writer...
@endhasrole
@hasanyrole($collectionOfRoles)
    I have one or more of these roles!
@else
    I have none of these roles...
@endhasanyrole
// or
@hasanyrole('writer|admin')
    I am either a writer or an admin or both!
@else
    I have none of these roles...
@endhasanyrole
@hasallroles($collectionOfRoles)
    I have all of these roles!
@else
    I do not have all of these roles...
@endhasallroles
// or
@hasallroles('writer|admin')
    I am both a writer and an admin!
@else
    I do not have all of these roles...
@endhasallroles

权限

@can('edit articles')
  //
@endcan

@if(auth()->user()->can('edit articles') && $some_other_condition)
  //
@endif

多用户认证使用

// Create a superadmin role for the admin users
$role = Role::create(['guard_name' => 'admin', 'name' => 'superadmin']);

// Define a `publish articles` permission for the admin users belonging to the admin guard
$permission = Permission::create(['guard_name' => 'admin', 'name' => 'publish articles']);

// Define a *different* `publish articles` permission for the regular users belonging to the web guard
$permission = Permission::create(['guard_name' => 'web', 'name' => 'publish articles']);

检查是否

$user->hasPermissionTo('publish articles', 'admin');

所有的操作,跟上面都加第二个参数,指明我的guard_name为admin

中间件

protected $routeMiddleware = [
    // ...
    'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
    'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
];

路由使用

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:super-admin|writer']], function () {
    //
});

Route::group(['middleware' => ['permission:publish articles|edit articles']], function () {
    //
});

控制器

 $this->middleware(['role:super-admin','permission:publish articles|edit articles']);

修改403

public function render($request, Exception $exception)
{
    if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
        // Code here ...
    }

    return parent::render($request, $exception);
}

命令行

php artisan permission:create-role writer

php artisan permission:create-role writer

php artisan permission:create-role writer web

php artisan permission:create-permission "edit articles" web

缓存

$user->assignRole('writer');
$user->removeRole('writer');
$user->syncRoles(params);
$role->givePermissionTo('edit articles');
$role->revokePermissionTo('edit articles');
$role->syncPermissions(params);
$permission->assignRole('writer');
$permission->removeRole('writer');
$permission->syncRoles(params);

以上会自动刷新缓存,如果你是使用数据库缓存,将不会看到结果,需要手动设置

php artisan cache:forget spatie.permission.cache

错误设置

比如你没有这个权限,会报没有这个权限规则,那怎么办呢

app/Exceptions/Handler.php

public function render($request, Exception $exception)
    {
        if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
            abort(401,'没有权限');
        }
        //找不到报错
        if ($exception instanceof \Spatie\Permission\Exceptions\PermissionDoesNotExist) {
            abort(401,'没有权限');
        }
        return parent::render($request, $exception);
    }

提示

评论区 (0)

没有记录
支持 markdown,图片截图粘贴拖拽都可以自动上传。
黑白课堂

黑白课堂

混元大罗金仙 站长创业者玉树凌风每天醒来0收入

查看更多

最新视频课程

Laravel 的 PhpSpreadsheet 包入门

wap2App 入门讲解,100%速成,全面为你讲解。

ace.js 打造一款属于你的 Web 编辑器,入门文档。

Laravel Permission 中文文档

解释 OAuth 2.0 认证 和使用场景说明

Laravel 之 horizon 队列管理界面系统

钻级赞助商