3
votes

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? - Laurence
@TheShiftExchange I am doing it in a FormValidation - Faiz Ahmed

2 Answers

1
votes

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.

0
votes

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.