I’ve looked around but I haven’t been able to find a way to perform an existence check of a resource before validating an incoming request with Laravel 8 FormRequest classes.
Basically, I want to perform the following steps when, say, for example, a PUT/PATCH request comes for the update of a resource:
- Check if the requested resource exists
- Check if the user is authorized to make the update
- Validate the fields of the request
- Update the resource
- Send the response back to the user
From what I’ve read, it’s easy to perform steps 2 and 3 in a FormRequest while 4 and 5 could be done in a Controller (or 4 in a Service and 5 in a Controller).
What I’m missing is how to perform step 1 right at the beginning. I’ve seen some workarounds like How to throw a 404 in Laravel Form Request with custom Rule maybe alongside How to validate Route Parameters in Laravel 5? but I don’t feel that is the proper way to achieve what I’d like to do…
With an existence check in the Controller the user gets to make a valid request first, even though he’s trying to update a resource that doesn’t exist (as the Framework throws a ValidationException before the Controller method can be invoked) and that doesn’t sound right.
Any suggestion on how to “delay” the validation after the existence check could be achieved? Otherwise, should I discard using FormRequests altogether?
Thanks in advance!
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
What you looking for are database transactions. it will make sure to execute the request only if everything is fine. for more info https://laravel.com/docs/5.8/database#database-transactions
Turns out that this is the default when type-hinting resources to controllers. The existence check comes first, then authorization and only after these comes validation.