Laravel-permission 用户权限管理扩展包的简单使用

  • 2019 年 12 月 17 日
  • 笔记

在 Laravel 中实现用户鉴权也是一个相当容易的事, Laravel 给我们提供了自带的鉴权方法 Gates 和 Policies ,但是相比较复杂的业务场景,自带的满足不了日常开发。幸运的是,Laravel 这款框架就是扩展多,许多牛人都开发了很多扩展,这些扩展都是开箱即用的(这也是我喜欢 Laravel 的原因)。 那么 Laravel-permission 这个扩展就是多角色用户权限的扩展、作者一直在维护。

安装

通过 Composer 安装

composer require spatie/laravel-permission

生成数据库迁移文件

php artisan vendor:publish --provider="SpatiePermissionPermissionServiceProvider" --tag="migrations"

执行迁移

php artisan migrate

生成配置文件

php artisan vendor:publish --provider="SpatiePermissionPermissionServiceProvider" --tag="config"

配置文件存放在 config/permission.php ,一般来说不需要做额外其他改动

return [        'models' => [            /*           * When using the "HasPermissions" trait from this package, we need to know which           * Eloquent model should be used to retrieve your permissions. Of course, it           * is often just the "Permission" model but you may use whatever you like.           *           * The model you want to use as a Permission model needs to implement the           * `SpatiePermissionContractsPermission` contract.           */            'permission' => SpatiePermissionModelsPermission::class,            /*           * When using the "HasRoles" trait from this package, we need to know which           * Eloquent model should be used to retrieve your roles. Of course, it           * is often just the "Role" model but you may use whatever you like.           *           * The model you want to use as a Role model needs to implement the           * `SpatiePermissionContractsRole` contract.           */            'role' => SpatiePermissionModelsRole::class,        ],        'table_names' => [            /*           * When using the "HasRoles" trait from this package, we need to know which           * table should be used to retrieve your roles. We have chosen a basic           * default value but you may easily change it to any table you like.           */            'roles' => 'roles',            /*           * When using the "HasPermissions" trait from this package, we need to know which           * table should be used to retrieve your permissions. We have chosen a basic           * default value but you may easily change it to any table you like.           */            'permissions' => 'permissions',            /*           * When using the "HasPermissions" trait from this package, we need to know which           * table should be used to retrieve your models permissions. We have chosen a           * basic default value but you may easily change it to any table you like.           */            'model_has_permissions' => 'model_has_permissions',            /*           * When using the "HasRoles" trait from this package, we need to know which           * table should be used to retrieve your models roles. We have chosen a           * basic default value but you may easily change it to any table you like.           */            'model_has_roles' => 'model_has_roles',            /*           * When using the "HasRoles" trait from this package, we need to know which           * table should be used to retrieve your roles permissions. We have chosen a           * basic default value but you may easily change it to any table you like.           */            'role_has_permissions' => 'role_has_permissions',      ],        'column_names' => [            /*           * Change this if you want to name the related model primary key other than           * `model_id`.           *           * For example, this would be nice if your primary keys are all UUIDs. In           * that case, name this `model_uuid`.           */          'model_morph_key' => 'model_id',      ],        /*       * When set to true, the required permission/role names are added to the exception       * message. This could be considered an information leak in some contexts, so       * the default setting is false here for optimum safety.       */        'display_permission_in_exception' => false,        'cache' => [            /*           * By default all permissions are cached for 24 hours to speed up performance.           * When permissions or roles are updated the cache is flushed automatically.           */            'expiration_time' => DateInterval::createFromDateString('24 hours'),            /*           * The cache key used to store all permissions.           */            'key' => 'spatie.permission.cache',            /*           * When checking for a permission against a model by passing a Permission           * instance to the check, this key determines what attribute on the           * Permissions model is used to cache against.           *           * Ideally, this should match your preferred way of checking permissions, eg:           * `$user->can('view-posts')` would be 'name'.           */            'model_key' => 'name',            /*           * You may optionally indicate a specific cache driver to use for permission and           * role caching using any of the `store` drivers listed in the cache.php config           * file. Using 'default' here means to use the `default` set in cache.php.           */            'store' => 'default',      ],  ];

使用

首先,laravel-permission 提供了 一个 trait —— HasRoles,该 trait 方便我们使用 扩展包提供的权限角色等操作方法。

SpatiePermissionTraitsHasRoles trait 添加到用户模型中

use IlluminateFoundationAuthUser as Authenticatable;  use SpatiePermissionTraitsHasRoles;    class User extends Authenticatable  {      use HasRoles;        // ...  }

简单用法

新增角色

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

新增权限

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

为角色添加权限

$role->givePermissionTo('edit articles');

赋于用户某个角色

// 单个角色  $user->assignRole('writer');    // 多个角色  $user->assignRole('writer', 'admin');    // 数组形式的多个角色  $user->assignRole(['writer', 'admin']);

检查用户角色

// 是否是admin  $user->hasRole('admin');    // 是否拥有至少一个角色  $user->hasAnyRole(Role::all());    // 是否拥有所有角色  $user->hasAllRoles(Role::all());   

检查用户权限

// 检查用户是否有某个权限  $user->can('edit articles');    // 检查角色是否拥有某个权限  $role->hasPermissionTo('edit articles');  

直接给用户添加权限

// 为用户添加‘直接权限’  $user->givePermissionTo('edit articles');    // 获取所有直接权限  $user->getDirectPermissions() 

撤销用户权限

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

撤销权限、并添加新的权限

$user->syncPermissions(['edit articles', 'delete articles']);

更多用户查阅 官方文档 https://github.com/spatie/laravel-permission

(adsbygoogle = window.adsbygoogle || []).push({});