Form Request Validation in Laravel API’s

Form Request Validation in Laravel API’s

When we write API’s in Laravel and use Form Requests to validate the requests, the default Laravel behavior is to throw Validation Exception (\Illuminate\Validation\ValidationException) and redirect the user to the previous page. This redirect URL can be configured as well if we want to. As a result of it, we see a response with 200 status code, and the response body contains a big data set comprised of HTML, Javascript and CSS: a complete HTML page is sent as a response because of the redirection.

To get a proper failure response with correct status code and error messages, we have the following options.


First Method

Inside our FormRequest class, we can override the withValidator function. This withValidator function takes a Validator instance (\Illuminate\Contracts\Validation\Validator) as an input argument. The Validator object has a fails method available. We can explicitly check for the failure of our validation and send an appropriate error message with the correct HTTP status code.

firstMethod


Second Method

Inside our FormRequest class, we can override the failedValidation function. This failedValidation function takes a Validator instance (\Illuminate\Contracts\Validation\Validator) as an input argument. Inside this method, we can throw a Validation Exception (\Illuminate\Validation\ValidationException).

secondMethod


Third Method

Laravel handles all exceptions in the App\Exceptions\Handler class for us. Here inside the register method, we can capture the Validation Exception thrown by Laravel in case of validation failures and send an appropriate response back to the API consumer.

thirdMethod

Founded
2014
Years in business
12
People
66
Headquarters
Lahore, Pakistan
Projects delivered
250+
AI systems in production
10