2016-09-24 8 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

감사합니다! $ role-> perms-> contains ($ permission); 나를 위해 일한다. – Ildar