I have a boilerplate Laravel 9 app, with a model generated with the cli command php artisan make:model Post -a --api
to make an API controller, with form request and policies.
The Laravel Policy Authorisation docs doesn’t seem to make it clear what to do with both a Policy and FormRequest. Do I call the policy class inside the FormRequest? Or ignore the policies for store/update?
How do I use auth policies with FormRequests for my API controller?
2
Answers
Docs didn't make it clear, posting incase anyone else is struggling. Example for User model, UserPolicy and UserController.
First, add the Policy class in AuthServiceProvider.
Second, use authorizeResources in the controller to auto map policies to the api controller. See here for what the policy -> controller maps to
Last, DELETE the authorize section from the FormRequests
Now the policies set in UserPolicy will be used as auth guards for the User Controller.
Although its not told directly in the docs. You can use the policy inside the
authorize()
method in aForm Request
:Authorization Using Model
Controller
So Instead of using
$this->authorize('update', $post)
inside the controller you can directly put it inside theFormRequest
.Hope it helps : )