请自动参照到上上篇文章
1、创建控制器
php artisan make:model Permission
php artisan make:model Role
2、创建表
php artisan make:migration create_roles_table --create=roles
编辑migration文件中的up方法
Schema::create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('label')->nulllabel(); $table->timestamps(); }); Schema::create('permissions', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('label')->nulllabel(); $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('user_id') ->references('id') ->on('users') ->onDelete('cascade'); $table->foreign('role_id') ->references('id') ->on('roles') ->onDelete('cascade'); $table->primary(['user_id', 'role_id']); });
生成表
php artisan migrate
3、添加Permisssion和Role的映射关系
Permisssion.php
public function roles() { return $this->belongsToMany(Role::class); }
Role.php
public function permissions() { return $this->belongsToMany(permission::class); } public function givePermission(Permission $permission){ return $this->permissions()->save($permission); }
4、使用tinker添加测试数据
至此我们已经在roles、permission、permission_role表中各添加一条数据,以上也可以在phpmyadmin中完成
5、从数据库中读取权限并且定义权限
AuthServiceProvider.php
public function boot(GateContract $gate) { parent::registerPolicies($gate); foreach($this->getPermissions() as $permission) { $gate->define($permission->name, function(User $user) use($permission){ return $user->hasRole($permission->roles); }); } } protected function getPermissions() { return $getDate = Permission::with('roles')->get(); }
6、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(); }
7、添加一条user和role的映射关系
经测试和上篇文章的结果是一样的,不同的是这里的权限(edit_form)是从数据库里读取出来的