wileecoyote
wileecoyote

Reputation: 83

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!

Upvotes: 0

Views: 1087

Answers (2)

wileecoyote
wileecoyote

Reputation: 83

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.

Upvotes: 0

Amir Saadallah
Amir Saadallah

Reputation: 686

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

Upvotes: 0

Related Questions