2 years ago

Applying authorisation policy for nested resource

Posted 2 years ago by Martinkovic


I'm listing answers to specific question by this route: GET api/question/{question}/answer . Currently, I am trying to apply policy that will ensure that only owner of the question can list respective answers to it.

I've managed to implement this policy by assigning it to answer model in AuthServiceProvider. However I'm wondering if it should be assigned to answer or to question model. For example there is situation when there are no answers to the question and policy authorisation is based on retrieval of question_id and respective owner_id from relations with answers, but when there is no answer, my answer policy is unable to retrieve and validate these ids and therefore throws action unauthorised exception.

If the policy will be assigned to question model there will be no such problem, however I'm not sure if it's semantically correct to assign it to question model when I want to check rights to indexing of answers and not questions.

Chunks of related code:

index method:

public function index(Question $question){

    return QuestionAnswerResource::collection($question->answers);


public function index(User $user, QuestionAnswer $answer)
        $campaign = Campaign::find($answer->question->campaign_id);

        return $user->id == $campaign->user->id;


Please sign in or create an account to participate in this conversation.