无为清净楼资源网 Design By www.qnjia.com

想要在Laravel中使用Entrust,首先需要通过Composer来安装其依赖包:

composer require zizaco/entrust 5.2.x-de

安装完成后需要在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

该命令会在 config 目录下创建一个 entrust.php 文件。

3、用户角色权限表

接下来我们使用Entrust提供的迁移命令生成迁移文件:

php artisan entrust:migration

如果执行上面的 命令出现 以下的错误:

使用Entrust扩展包在laravel 中实现RBAC的功能 

处理方法: vendor-> zizaco-> entrust-> src-> commands-> MigrationCommand.php ,并将”fire“方法更改为”handle“ 然后通过以下命令生成相应的数据表:

php artisan migrate

最终会生成4张新表:

  • roles —— 存储角色
  • permissions —— 存储权限
  • role_user —— 存储角色与用户之间的多对多关系
  • permission_role —— 存储角色与权限之间的多对多关系

4、模型类

Role
我们需要创建Role模型类app/Role.php并编辑其内容如下:

<"htmlcode">
<"htmlcode">
<"htmlcode">
$role = Role::findOrFail(1); // 获取给定权限

// 正常删除
$role->delete();
// 强制删除
$role->users()->sync([]); // 删除关联数据
$role->perms()->sync([]); // 删除关联数据

$role->forceDelete(); // 不管透视表是否有级联删除都会生效

总结

标签:
Entrust扩展包实现RBAC,laravel,Entrust扩展包

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com