前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Laravel-permission 用户权限管理扩展包的简单使用

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

作者头像
hedeqiang
发布2019-12-17 21:30:58
1.9K0
发布2019-12-17 21:30:58
举报
文章被收录于专栏:LaravelCode

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

安装

通过 Composer 安装

代码语言:javascript
复制
composer require spatie/laravel-permission

生成数据库迁移文件

代码语言:javascript
复制
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"

执行迁移

代码语言:javascript
复制
php artisan migrate

生成配置文件

代码语言:javascript
复制
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"

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

代码语言:javascript
复制
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
         * `Spatie\Permission\Contracts\Permission` contract.
         */

        'permission' => Spatie\Permission\Models\Permission::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
         * `Spatie\Permission\Contracts\Role` contract.
         */

        'role' => Spatie\Permission\Models\Role::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 方便我们使用 扩展包提供的权限角色等操作方法。

Spatie\Permission\Traits\HasRoles trait 添加到用户模型中

代码语言:javascript
复制
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;

    // ...
}

简单用法

新增角色

代码语言:javascript
复制
use Spatie\Permission\Models\Role;
$role = Role::create(['name' => 'writer']);

新增权限

代码语言:javascript
复制
use Spatie\Permission\Models\Permission;

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

为角色添加权限

代码语言:javascript
复制
$role->givePermissionTo('edit articles');

赋于用户某个角色

代码语言:javascript
复制
// 单个角色
$user->assignRole('writer');

// 多个角色
$user->assignRole('writer', 'admin');

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

检查用户角色

代码语言:javascript
复制
// 是否是admin
$user->hasRole('admin');

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

// 是否拥有所有角色
$user->hasAllRoles(Role::all());   

检查用户权限

代码语言:javascript
复制
// 检查用户是否有某个权限
$user->can('edit articles'); 

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

直接给用户添加权限

代码语言:javascript
复制
// 为用户添加『直接权限』
$user->givePermissionTo('edit articles');

// 获取所有直接权限
$user->getDirectPermissions() 

撤销用户权限

代码语言:javascript
复制
$user->revokePermissionTo('edit articles');

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

代码语言:javascript
复制
$user->syncPermissions(['edit articles', 'delete articles']);

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装
  • 使用
  • 简单用法
相关产品与服务
数据传输服务
腾讯云数据传输服务(Data Transfer Service,DTS)可帮助用户在业务不停服的前提下轻松完成数据库迁移上云,利用实时同步通道轻松构建高可用的数据库多活架构,通过数据订阅来满足商业数据挖掘、业务异步解耦等场景需求。同时,DTS 还提供私有化独立输出版本 DTS-DBbridge,支持异构数据库和同构数据库之间迁移和同步,可以帮助企业实现完整数据库迁移(如 Oracle)。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档