How to check for resource existence before validation in Laravel with FormRequests

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:

  1. Check if the requested resource exists
  2. Check if the user is authorized to make the update
  3. Validate the fields of the request
  4. Update the resource
  5. 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!

Answers:

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.

Method 1

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

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x