laravel RBAC 权限管理 安装配置
Entrust为我们在Laravel中实现基于角色的权限管理(RBAC)提供了简洁灵活的方式。
安装:想要在Laravel中使用Entrust,首先需要通过Composer来安装其依赖包:
composer require zizaco/entrust 5.2.x-dev
安装完成后需要在config/app.php中注册服务提供者到providers数组:
Zizaco\Entrust\EntrustServiceProvider::class,
同时在该配置文件中注册相应门面到aliases数组:
'Entrust' => Zizaco\Entrust\EntrustFacade::class,
如果你想要使用中间件(要求Laravel 5.1或更高版本)还需要添加如下代码到app/Http/Kernel.php的routeMiddleware数组:
'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class,
配置
在配置文件config/auth.php中设置合适的值,Entrust会使用这些配置值来选择相应的用户表和模型类:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
'table' => 'users', //自己的用户表
],
],
你还可以发布该扩展包的配置以便后续自定义相关表名以及模型类的命名空间:
php artisan vendor:publish
用户角色权限表 接下来我们使用Entrust提供的迁移命令生成迁移文件:
php artisan entrust:migration
生成迁移文件时报错 ReflectionException:方法Zizaco \ Entrust \ MigrationCommand :: handle() 不存在
找到这个Zizaco\Entrust\MigrationCommand这个文件,然后里面又个fire方法改成handle方法即可
然后通过以下命令生成相应的数据表:
php artisan migrate
生成相应的数据表如果报错:找到database/migrations/例如:2019_02_18_111558_entrust_setup_tables.php
roles表name字段修改长度: permissions表的name字段长度需也需修改
用户角色管理表修改为自己的用户表
最终会生成4张新表:
roles —— 存储角色
permissions —— 存储权限
role_user —— 存储角色与用户之间的多对多关系
permission_role —— 存储角色与权限之间的多对多关系
模型类
我们需要创建Role模型类app/Role.php并编辑其内容如下:
<?php namespace App;
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
}
Role模型拥有三个主要属性:
name —— 角色的唯一名称,如“admin”,“owner”,“employee”等
display_name —— 人类可读的角色名,例如“后台管理员”、“作者”、“雇主”等
description —— 该角色的详细描述
display_name和description属性都是可选的,在数据库中的相应字段默认为空。
Permission
接下来创建Permission模型app/Permission.php并编辑其内容如下:
<?php namespace App;
use Zizaco\Entrust\EntrustPermission;
class Permission extends EntrustPermission
{
}
Permission模型也有三个主要属性:
name —— 权限的唯一名称,如“create-post”,“edit-post”等
display_name —— 人类可读的权限名称,如“发布文章”,“编辑文章”等
description —— 该权限的详细描述
User
接下来我们在User模型中使用EntrustUserTrait:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
还没有评论,来说两句吧...