Prevent redirect to homepage after invalid in Laravel Prevent redirect to homepage after invalid in Laravel laravel laravel

Prevent redirect to homepage after invalid in Laravel


Also this can be achieved without overriding any function. Laravel is built to support both Json & normal pages.Please change your settings in postman and set Accept to application/json like belowenter image description here

Laravel is SMART ;-)


Your custom FormRequest extends Illuminate\Foundation\Http\FormRequest. Within is a function that performs the redirect called response(). Simply override this function within your custom FormRequest to change how invalid validations are responded to.


namespace App\Http\Requests;use Illuminate\Foundation\Http\FormRequest;use Illuminate\Http\JsonResponse;class CustomFormRequest extends FormRequest{    /**     * Custom Failed Response     *     * Overrides the Illuminate\Foundation\Http\FormRequest     * response function to stop it from auto redirecting     * and applies a API custom response format.     *     * @param array $errors     * @return JsonResponse     */    public function response(array $errors) {        // Put whatever response you want here.        return new JsonResponse([            'status' => '422',            'errors' => $errors,        ], 422);    }}


I faced same problem in Laravel 8. In your request class, you can override failedValidation method.

<?php...use Illuminate\Contracts\Validation\Validator;use Illuminate\Http\Exceptions\HttpResponseException;class RegisterRequest extends FormRequest{    ...    protected function failedValidation(Validator $validator)    {        throw new HttpResponseException(response()->json(['errors' => $validator->errors()], 422));    }    ...}