0

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!

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

3 Comments

Actually I have no problem at using the firstOrFail method in the controller after validation has passed... and throw a 404 in the handler. The point I want to underline is that the user gets to make a valid request first, even though he's trying to update a resource that doesn't exist
it's the same but in a different order. what you can do is to try to get that resource in the controller if the returned is null then the request fails and no need to proceed to step 2
Agreed, but that means I should not use the FormRequest class because if the parameters are not valid then the Controller never gets called as a ValidationException is thrown before
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.