5

If the incoming request was an AJAX request, no redirect will be generated. Instead, an HTTP response with a 422 status code will be returned to the browser containing a JSON representation of the validation errors.

This is not working! I am trying to access the route via an ajax request and it redirects back.

If validation passes, your code will keep executing normally. However, if validation fails, an Illuminate\Contracts\Validation\ValidationException will be thrown. This exception is automatically caught and a redirect is generated to the user's previous location. The validation errors are even automatically flashed to the session!

Now I want to know where does laravel catch this exception so that I can modify it?

2
  • Are you doing this inside a Controller or a FormValidation? Commented Mar 8, 2015 at 12:14
  • @TheShiftExchange I am doing it in a FormValidation Commented Mar 8, 2015 at 14:08

2 Answers 2

2

This is handled inside the FormRequest class:

protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException($this->response(
        $this->formatErrors($validator)
    ));
}

You can override this function in your own Request object and handle a failed validation any way you like.

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

1 Comment

Still, the documentation says this behavior will be done by the framework. Isn't this an error?
0

After been researching for a while I will post my results so anyone with this problem saves a lot of time.

@Faiz, you technically shouldn't change a thing if you want to stick to laravel behavior (I'll always try to follow taylor's recommendations). So, to receive a 422 response code status you need to tell phpunit you will send a XMLHttpRequest. That said, this works on laravel 5

        $response = $this->call('POST', $url, [], [], [],
        ['HTTP_X_Requested-With' => 'XMLHttpRequest']);

More information at Github Issues. Besides, if you look at Symfony\Component\HttpFoundation\Request@isXmlHttpRequest you will find that this header is used by "common JavaScript frameworks" and refers to this link

Haven't tested on the browser yet, but I think this should work too.

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.