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

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

安装

通过 Composer 安装

composer require spatie/laravel-permission

生成数据库迁移文件

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"

执行迁移

php artisan migrate

生成配置文件

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --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
         * `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 添加到用户模型中

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;

    // ...
}

简单用法

新增角色

use Spatie\Permission\Models\Role;
$role = Role::create(['name' => 'writer']);

新增权限

use Spatie\Permission\Models\Permission;

$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

关于极客返利

极客返利 是由我个人开发的一款网课返利、返现平台。包含 极客时间返现、拉勾教育返现、掘金小册返现、GitChat返现。目前仅包含这几个平台。后续如果有需要可以考虑其他平台。 简而言之就是:你买课,我返现。让你花更少的钱,就可以买到课程。

https://geek.laravelcode.cn

https://geek.idaka.ink

版权许可

本作品采用 知识共享署名 4.0 国际许可协议 进行许可。

转载无需与我联系,但须注明出处,注明文章来源 Laravel-permission 用户权限管理扩展包的简单使用

联系我

编程怪事

你可能感兴趣的:(Laravel-permission 用户权限管理扩展包的简单使用)