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 两个链接,说明我们定义的权限控制起作用了。
(完)
91jufan 2015/12/16 09:41
这个可以有!
tt 2015/12/28 15:35
AuthServiceProvider 我没有看到这个文件哦,需要怎么生成呢
Specs 2015/12/28 15:42
@ 在 /app/Providers 下
net 2016/01/09 20:18
return !! $role->intersect($this->roles)->count();没看懂这段代码的两个"!"表示什么意思
net 2016/01/09 22:30
@ 明白了
Ppp 2016/01/15 18:37
想问问大神,插入YouTube视频后怎么居中,在手机上如何自适应,达到良好的现实效果
Specs 2016/01/17 11:05
@ 没用过youtube视频~
萧晔离 2016/01/18 13:40
在blade中使用@can来判断权限,貌似在视图中有效,在布局模板中不行,怎么解决?
Specs 2016/01/18 15:10
@ 你说的布局模版是指?
萧晔离 2016/02/16 17:14
@ 那个我搞定了,在控制器中怎么判断呢?用Auth::user()->hasPermission('xxx')报错Trying to get property of non-object
Specs 2016/02/16 22:00
@ 试试 Auth::user()->can('xxx') 或 $this->authorize('xxx');
萧晔离 2016/02/17 09:43
@ OK,搞定了~
liwenyu 2016/09/19 18:11
@ 你好,能告诉下是怎么搞定的么?
Simon 2016/03/23 22:32
@ 在控制如何控制 5.2的
Specs 2016/03/24 09:21
@ 一样的
Simon 2016/03/24 21:09
@ 好的,谢谢!
Robot5 2016/02/02 11:12
5.2照做不行啊!
Specs 2016/02/03 11:10
@ 还没用过5.2,有什么错误提示?
Robot5 2016/02/05 03:39
@ 主要是问题就是没错误,有人说是Windows环境的问题,用Linux就好了!但问题一直没找到!这里 laravist.com/discuss/347
Specs 2016/02/16 09:37
@ 有人说 5.2 需要加入 web 中间件,然后就可以了~我在Linux测试没有加也可以
Min 2016/03/10 15:13
你好,我用的是5.2,然后弄了2套认证,一个后台用户认证(admin),一个前台(user),按照教程,都是可以的,然后我将教程里的user都换成了admin就有点问题,在控制器中`$admin->can('edit-post')`是可以判断的,但是在视图中就不行了,一个权限的都显示不出来,这是为什么
Min 2016/03/10 15:22
@ 应该找到原因了,我把auth.php中默认的guard从web改成admin,就可以了,要是不改的话模版里的can好像是取的user表的用户,那请问我要是默认还是web,怎样让模版里的can取的后台用户admin
Specs 2016/03/10 16:18
@ 你的是两张不同的表吗?有个在 5.2 中用这种方法的说加入 web 中间件,然后就可以在 view 中使用了
alan 2016/03/14 20:27
您好,请问这个权限系统和Entrust 一样吗?用你这个是不是就可以替代Entrust? 因为我可能还得自定义一些方法,比如获取所有权限等等。
Specs 2016/03/14 20:47
@ 差不多,那个提供的功能多一些,用自带这个的话就是需要自己写方法。
Keroppi 2016/04/11 22:09
非常感谢,我是小白,想请教一下如何修改成ROUTE中间件呢?我想直接在路由group里用中间件指定可以访问的Role
Specs 2016/04/13 09:21
@ github.com/9IPHP/LaravelBlog 我这个项目中有,你可以参考下
Allen.dong 2016/05/30 17:12
为什么我数据库执行tinker会报错
Specs 2016/05/31 08:14
@ 报什么错?