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({});