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 big data set comprised of HTML, Javascript and CSS i.e. 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 withValidator function. This withValidator function takes Validator Instance (\Illuminate\Contracts\Validation\Validator) as an input argument. Validator object has fails method available. We can explicitly check for the failure of our validation and can send an appropriate error message with the correct HTTP Status Code.

Second Method

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

Third Method

Laravel handles all the exceptions in 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 can send an appropriate response back to the API consumer.

Contact Us

Address

What Market Says About Us!