2016-09-24 39 views
0

我有很多关系rolespermissions模型。我有一个操作控制器来附加和分离用户的权限。如何检查某些权限是否被分离到某个角色?如何检查模型实例是否附加到laravel 5.3中的相关模型实例?

控制器:

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); 
     } 

    } 
} 

回答

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; })

+0

谢谢! $角色的> perms->包含($许可);为我工作 – Ildar

相关问题