Laravel在5.1.11版本中加入了Authorization,可以让用户自定义权限,今天分享一种定义权限系统的方法。
1. 创建角色与权限表
使用命令行创建角色与权限表:
php artisan make:migration create_permissions_and_roles --create=permissions
之后打开刚刚创建的文件,填入下面的代码:
public function up() { Schema::create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('label'); $table->string('description')->nullable(); $table->timestamps(); }); Schema::create('permissions', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('label'); $table->string('description')->nullable(); $table->timestamps(); }); Schema::create('permission_role', function (Blueprint $table) { $table->integer('permission_id')->unsigned(); $table->integer('role_id')->unsigned(); $table->foreign('permission_id') ->references('id') ->on('permissions') ->onDelete('cascade'); $table->foreign('role_id') ->references('id') ->on('roles') ->onDelete('cascade'); $table->primary(['permission_id', 'role_id']); }); Schema::create('role_user', function (Blueprint $table) { $table->integer('user_id')->unsigned(); $table->integer('role_id')->unsigned(); $table->foreign('role_id') ->references('id') ->on('roles') ->onDelete('cascade'); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); $table->primary(['role_id', 'user_id']); }); } public function down() { Schema::drop('roles'); Schema::drop('permissions'); Schema::drop('permission_role'); Schema::drop('role_user'); }
上面的代码会创建角色表、权限表、角色与权限的中间表以及角色与用户的中间表。
2. 创建模型
接下来使用命令行分别创建角色与权限模型:
php artisan make:model Permission php artisan make:model Role
然后分别打开Permission.php、Role.php 以及 User.php ,加入下面的代码:
// Permissions.php public function roles() { return $this->belongsToMany(Role::class); } // Role.php public function permissions() { return $this->belongsToMany(Permission::class); } //给角色添加权限 public function givePermissionTo($permission) { return $this->permissions()->save($permission); } // User.php public function roles() { return $this->belongsToMany(Role::class); } // 判断用户是否具有某个角色 public function hasRole($role) { if (is_string($role)) { return $this->roles->contains('name', $role); } return !! $role->intersect($this->roles)->count(); } // 判断用户是否具有某权限 public function hasPermission($permission) { return $this->hasRole($permission->roles); } // 给用户分配角色 public function assignRole($role) { return $this->roles()->save( Role::whereName($role)->firstOrFail() ); }
上面的代码实现了给角色分配权限及给用户分配角色,然后还提供了判断用户是否具有某角色及某权限的方法。
之后就给使用Laravel提供的Authorization来定义权限控制了,打开 /app/Providers/AuthServiceProvider.php
文件,在 boot()
中添加代码:
public function boot(GateContract $gate) { parent::registerPolicies($gate); $permissions = \App\Permission::with('roles')->get(); foreach ($permissions as $permission) { $gate->define($permission->name, function($user) use ($permission) { return $user->hasPermission($permission); }); } }
通过上面的方法就定义好了各个权限。下面就该填充数据了。
3. 填充数据
为方便起见,这里使用 tinker 命令行工具来添加几条测试数据:
php artisan tinker
之后进入命令行,依次输入下列命令:
// 改变命名空间位置,避免下面每次都要输入 App namespace App // 创建权限 $permission_edit = new Permission $permission_edit->name = 'edit-post' $permission_edit->label = 'Can edit post' $permission_edit->save() $permission_delete = new Permission $permission_delete->name = 'delete-post' $permission_delete->label = 'Can delete post' $permission_delete->save() // 创建角色 $role_editor = new Role $role_editor->name = 'editor'; $role_editor->label = 'The editor of the site'; $role_editor->save() $role_editor->givePermissionTo($permission_edit) $role_admin = new Role $role_admin->name = 'admin'; $role_admin->label = 'The admin of the site'; $role_admin->save() // 给角色分配权限 $role_admin->givePermissionTo($permission_edit) $role_admin->givePermissionTo($permission_delete) // 创建用户 $editor = factory(User::class)->create() // 给用户分配角色 $editor->assignRole($role_editor->name) $admin = factory(User::class)->create() $admin->assignRole($role_admin->name)
上面我们创建了两个权限:edit-post 和 delete-post,然后创建了 editor 和 admin 两个角色,editor 角色拥有 edit-post 的权限,而 admin 两个权限都有。之后生成了两个用户,分别给他们分配了 editor 和 admin 的角色,即:ID 1 用户拥有 editor 角色,因此只有 edit-post 权限,而 ID 2 用户拥有 admin 角色,因此具有 edit-post 和 delete-post 权限。下面我们来验证下是否正确。
打开 routes.php 文件:
Route::get('/', function () { $user = Auth::loginUsingId(1); return view('welcome'); })
上面我们先验证 ID 1 用户的权限,然后修改 /resources/views/welcome.blade.php
文件:
<!DOCTYPE html> <html> <head> <title>Laravel</title> </head> <body> <h1>权限测试</h1> <p> @can('edit-post') <a href="#">Edit Post</a> @endcan </p> <p> @can('delete-post') <a href="#">Delete Post</a> @endcan </p> </body> </html>
在视图中我们通过 Laravel 提供的 @can
方法来判断用户是否具有某权限。
打开浏览器,访问上面定义的路由,可以看到视图中只出现了 Edit Post 链接。之后我们修改路由中用户ID为 2 ,然后再次刷新浏览器,可以看到,这次同时出现了 Edit Post 和 Delete Post 两个链接,说明我们定义的权限控制起作用了。
(完)
小南 2016/06/29 10:23
您好 我想问下 我从填充数据哪里开始就不行了 php artisan tinker 这个命令会报错 然后 下面一堆代码是命令还是什么 没看懂
Specs 2016/06/30 21:32
@ 贴错误代码
kylesean 2016/07/23 22:52
你是谁啊,用人家的代码,一个不剩的copy下来?
Specs 2016/07/24 16:11
@ 我用谁的代码?
EspecializaTi 2016/11/30 13:02
@ 用的老外的吧
呵呵哒 2017/02/28 12:31
@ 使用的是laracasts视频上面的acl涉及到的代码吧???难道不是?
Specs 2017/03/05 09:41
@ Youtube 上找的几段代码合起来的
lara 2016/09/12 15:40
你好,我用你的方法,切换成2套ACL的时候,如何在 public function boot(GateContract $gate) { parent::registerPolicies($gate); $permissions = \App\Permission::with('roles')->get(); foreach ($permissions as $permission) { $gate->define($permission->name, function($user) use ($permission) { return $user->hasPermission($permission); }); } } 根据用户信息判断用户是管理员还是普通用户啊,现在这里没办法获取用户信息,求指点
Specs 2016/09/12 22:16
@ 怎么换成的 2 套?在这里面多定义几个角色不就解决了~
lara 2016/09/13 09:15
@ 因为需求是普通用户中多一些特权用户,教师可以处理学生们的提问,这个是在普通用户中处理,然后后台用户是普通的,现在在AuthServiceProvider.php中没办法获取用户信息,也没办法使用auth这类,该怎么判断,这个用户是普通用户/管理员用户,然后赋予不同的权限啊?
lara 2016/09/13 17:10
@ 我搞定了,在boot方法中 Gate::before(function($user) {// 这里可以是调用方法 isAdmin() 只要能确定这个用户是前台还是后台用户就行if (!$user->isAdmin) { $permissions = \App\UserPermission::with('roles')->get(); } else { $permissions = \App\Permission::with('roles')->get(); } foreach ($permissions as $permission) { Gate::define($permission->name, function($user) use ($permission) { return $user->hasPermission($permission); }); }});
larastu 2016/09/29 13:56
$permissions = \App\Permission::with('roles')->get();这获取的是全部,如果要获取登录用的权限怎么处理
Specs 2016/09/30 08:57
@ 可以加 where 条件呀~
larastu 2016/09/30 10:53
@ 问题是你咋知道谁登录啊 你没法知道啊
lara 2016/09/30 17:42
@ Gate::before(function ($user) { dd($user); 这里可以得到用户信息,然后就可以判断了吧})
williambear 2016/10/31 17:05
[Illuminate\Database\QueryException]SQLSTATE[42S02]: Base table or view not found: 1146 Table 'inagent.permissions' doesn't exist (SQL: select * from `permissions`)帮忙看看到底是啥回事!谢谢了![PDOException]SQLSTATE[42S02]: Base table or view not found: 1146 Table 'inagent.permissions' doesn't exist
Specs 2016/11/01 21:48
@ 没有那个表
leedaning 2016/11/23 10:11
你好,我按照教程的做的,但是会报错,貌似是Model里的数据。找不到问题所在,麻烦给看下吧。FatalErrorException in Permission.php line 13:syntax error, unexpected 'protected' (T_PROTECTED)
leedaning 2016/11/23 16:33
@ 已经找到原因了,是我Model里面写错了。
Specs 2016/11/27 05:32
@ 发个全点的
dd 2016/12/06 15:21
win7系统 5.2 使用了之后没有反应· 有什么办法吗
Protity 2016/12/24 18:45
我想在路由中间件中 对于每个控制器_动作 验证权限。我现在是加的中间件是public function handle($request, Closure $next,GateContract $gate) {// $permissions = AdminPermission::with('roles')->get(); $action = \Route::current()->getActionname(); $action = explode('\\',$action); foreach ($action as $item) { if(strpos($item,'@')){ $perssion = str_replace('@','_',$item); break; } } if($gate->denies($perssion)){ echo '123'; }else{ echo 'bbb'; } return $next($request); }总是提示我 Type error: Too few arguments to function App\Http\Middleware\AdminHasRoleMiddleware::handle(), 2 passed and exactly 3 expected
Specs 2016/12/26 21:50
@ 参数多了
Protity 2016/12/24 18:47
public function handle($request, Closure $next) {// $permissions = AdminPermission::with('roles')->get(); $action = \Route::current()->getActionname(); $action = explode('\\',$action); foreach ($action as $item) { if(strpos($item,'@')){ $perssion = str_replace('@','_',$item); break; } } if(Gate::denies($perssion)){ echo '123'; }else{ echo 'bbb'; } return $next($request); }我改成这样,就会提示我 Non-static method Illuminate\Auth\Access\Gate::denies() should not be called statically求教 我哪里做错了,或者 我应该怎么做,谢谢。
Specs 2016/12/26 21:50
@ 提示 denies() 方法不能通过静态方式调用~~
Inner 2016/12/28 14:24
你好,我按照的步骤没有报错却没有出现这个结果,database里面是这样的:permissions:'1', 'edit-post', 'Can edit post', NULL, '2016-12-27 18:39:46', '2016-12-27 18:39:46''2', 'delete-post', 'Can delete post', NULL, '2016-12-27 18:42:59', '2016-12-27 18:42:59' permission_role: '1', '4''1', '5' roles:'4', 'editor', 'site', NULL, '2016-12-27 18:47:42', '2016-12-27 18:47:42''5', 'admin', 'The admin of the site', NULL, '2016-12-27 18:49:12', '2016-12-27 18:49:12' role_user: '1', '5''9', '5''11', '1''12', '5'我调用的是 : $user = Auth::loginUsingId(9);能帮忙看看是什么原因吗
Specs 2017/01/11 22:00
@ 哪个版本的