我对roles
和permissions
模型有很多关系。我有一个动作控制器,用于附加和分离用户的权限。如何检查某个角色是否分离了一些权限?
控制器:
class RolePermissionController extends Controller
{
// POST /roles/1/permissions/2/sync
// BODY {isAllowed: true}
// $role - instance of role model with id == 1
// $permission - instance of permission model with id == 2
// roles and permissions has many to many relationship
public function synchronize(Request $request, Role $role, Permission $permission)
{
$this->authorize($permission);
$this->validate($request, [
'isAllowed' => 'required|boolean'
]);
// I want to check here if the permission is attached to the role
if ($request->input('isAllowed')) {
$role->perms()->attach($permission);
} else {
$role->perms()->detach($permission);
}
}
}
答案 0 :(得分:1)
$role->whereHas('perms', function($query) use($permission) { $query->where('perms.id', $permission->id); })->count();
或者,假如您已经加载了权限:
$role->perms->contains(function($value) use($permission) { return $value->id == $permission->id; })
答案 1 :(得分:0)
我只是使用第一个模型的关联方法来访问连接表的查询构建器,然后询问相关模型列的计数。在你的情况下,我认为:
$ role-> perms() - >其中(' permission_id',$ permission-> id) - > count()> 0