How to prevent 422 console error with laravel validation
Is there any chance to prevent 422 console error with validation using form request? Everything works fine, I validate modal form with ajax but still receiving this annoying console error.
You can handle failed validation in the form request by overriding the failedValidation method.
But the console error is correct, you have gotten a 422 because the submitted form was unprocessable. I wouldn't stress about this error - 99.9% of users will not see the console.
You could also do this manually if your controller extends laravel's basecontroller Illuminate\Routing\Controller by accessing the validation factory, (this gives you a little bit more control) like this:
$validator = $this->getValidationFactory()->make($request->all(), [
'name' => 'required'
// etc.
];
if(!$validator->passes()) {
// Return JSON response on fail
}
// Continue as the validation passed.
Try doing a dd($request->all() to make sure you are posting the required data to the server. This will reduce the reasons why the request is unprocessable. Are you sending the token as well?
@RONALDJESSE - I use dedicate request for that with rules and custom messages. Everything works fine but I want to prevent 422 error even if I receive correct errors messages
If you do not want errors in the console, then you will need to return a 2xx response status code. To achieve this, you need to do as I suggested and override the failedValidation method in the FormRequest class(es) and return a custom response, e.g.
public function failedValidation(Validator $validator)
{
return response()->json($validator->errors());
}
Or, in app/Exceptions/Handler.php you can catch a ValidationException and response to all validation expections in the same manner.
Bear in mind if you decide to return a 2xx status code, your javascript HTTP client will not execute the error or catch callbacks for validation failures. Instead your success callback will need to check if it is a real success or a validation failed "success"