Search code examples
laravelrestmodelnested-resources

Laravel: How can I write a policy class for API methods on a nested resource controller?


I have a many to many relationship that I'm working with between User and Task models. A user belongs to many tasks and a task belongs to many users. I have a pivot table called task_user.

In my API, I have a route defined as follows:

Route::get('/users/{user}/tasks', 'TaskUserController@all');

I want to write a policy to enforce that the currently logged in user, auth()->user, is the user being requested in the route. Basically, a user can only view their own tasks.

How can I write a policy class for the nested resource controller TaskUserController?


Solution

  • Nesting of your resource has nothing to do with making policies.

    Make your UserPolicy.

    class UserPolicy()
    {
        public function view(User $authorizedUser, User $user) {
            return $authorizedUser->is($user);
        }
    }
    

    In your controller, you can authorize the action, with the authorize() helper. Alternatively it can be executed in your form request with Auth::user()->can().

    class TaskController {
        public function all(User $user)) {
            $this->authorize('view', $user);
    
            return $user->tasks;
        }
    }