我的控制器可以查看目标用户的权限:
public function view(Request $request, User $user){
$roles = Role::with('permissions')->get();
$permissions = Permission::get();
return view('adminarea.roles.view', compact('roles','user', 'permissions'));
}
刀片文件:
@foreach ( $permissions as $per )
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" name="permissions_ids[]" id="permissions"
value="{{ $per->id }}" style="margin-right:5px" @if (?)
checked="true"
@endif>
<label class="custom-control-label" for="permissions">{{ $per->name }}</label>
</div>
@endforeach
模型关系:
角色表:
public function users()
{
return $this
->belongsToMany('App\User')
->withTimestamps();
}
public function permissions()
{
return $this->belongsToMany(Permission::class, 'roles_permissions');
}
权限表:
public function roles()
{
return $this->belongsToMany(Role::class, 'roles_permissions');
}
用户表:
public function roles()
{
return $this->belongsToMany(Role::class, 'users_roles');
}
表结构:
这是我的role_permission模式:
Schema::create('roles_permissions', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->unsignedBigInteger('permission_id');
//FOREIGN KEY CONSTRAINTS
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
//SETTING THE PRIMARY KEYS
$table->primary(['role_id', 'permission_id']);
});
和users_role模式:
Schema::create('users_roles', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('role_id');
//FOREIGN KEY CONSTRAINTS
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
//SETTING THE PRIMARY KEYS
$table->primary(['user_id', 'role_id']);
});
权限表:
Schema::create('permissions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
和角色表架构:
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
答案 0 :(得分:0)
您可以在此处使用laravel策略。
为您的用户创建策略。
然后创建功能,例如canViewPosts,canAddPosts,canSeeViews等,并在每次检查时检查用户是否有权这样做。
UserPolicy示例
public function canView(User $user){
return $user->permissions->canView; //given you have permissions relation on user
}
然后在PostController中像
$this->authorize('canView', User::class);
在此处查看更多信息: https://laravel.com/docs/5.8/authorization#introduction