Paulund
2018-03-03 #laravel

Disable Validation Redirect In Laravel

In a previous tutorial we investigated how to validate requests in Laravel by using form request objects in your controller. You can view this tutorial by using this link How To Validate Requests In Laravel. This form object allows you to place all the validation rules in a single place making it very easy to reuse these in other requests. We also learnt how we can get the validated data out of the request object by using the validated(). Now we're going to see what happens on failing validation. The request object will run the command failedValidation method.


/**
  * Handle a failed validation attempt.
  *
  * @param  \Illuminate\Contracts\Validation\Validator  $validator
  * @return void
  *
  * @throws \Illuminate\Validation\ValidationException
  */
  protected function failedValidation(Validator $validator)
  {
      throw (new ValidationException($validator))
                ->errorBag($this->errorBag)
                ->redirectTo($this->getRedirectUrl());
  }

This is the default code that runs in Laravel, as you can see it will throw and new ValdiationException and then redirect the user to a defined URL. You can change where Laravel redirects the user by overriding one of the redirect properties redirect, redirectRoute, redirectAction. But what do you do if you don't want to redirect on failed validation. For example you might have an AJAX request where you need to validate the input but don't want to redirect and you just want to return a 422 validation error. To do this in your form request you can override this failedValidation method and return a new HTTP exception with the validation errors.


/**
 * Failed validation disable redirect
 *
 * @param Validator $validator
 */
protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException(response()->json($validator->errors(), 422));
}

This will not return a JSON of validation errors with a 422 status response and will now no longer redirect to the previous page.