3

In my RegisterController in Laravel I'm having trouble returning the errors to my front-end. Our application is built as a REST API, so the registration of a new user happens through an AJAX post to the registration route. This works fine if the validation passes, but if the validation fails, no errors are shown. It just redirects to a Laravel homepage. We are not using Blade for the front-end, so it's not possible to get the default validation errors from Blade. The front-end is a ReactJS client that communicates with the back-end through AJAX calls.

How do I get a JSON with the fields that didn't pass validation back to my front-end?

protected function validator(array $data)
{
    return Validator::make($data, [
        'first_name' => 'required|string|max:255',
        'last_name'  => 'required|string|max:255',
        'email'      => 'required|string|email|max:255|unique:users',
        'password'   => 'required|string|min:6|confirmed',
        'birth_year' => 'required|integer|min:4',
        'lat'        => 'required|numeric',
        'lon'        => 'required|numeric',
    ]);        
}

3 Answers 3

5

you can solve it by return the errors as json respone

$validator = Validator::make($data, [
    'first_name' => 'required|string|max:255',
    'last_name'  => 'required|string|max:255',
    'email'      => 'required|string|email|max:255|unique:users',
    'password'   => 'required|string|min:6|confirmed',
    'birth_year' => 'required|integer|min:4',
    'lat'        => 'required|numeric',
    'lon'        => 'required|numeric',
]);        

if ($validator->fails()) {    
  return response()->json($validator->messages(), 200);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your code is fine, you can catch the errors because laravel will automatically return a JSON response with a 422 HTTP status.

So basically in your ajax use the error function, if the validator fails ajax will automatically execute the code you have in your error from ajax.

For more info on how to properly handle error's for your ajax please take a look at this question. Displaying validation errors in Laravel 5 with React.js and AJAX

Comments

0

I solved the problem by disabling the 'guest' middleware in the RegisterController. I'm not sure if this is a solid solution, but for now it works.

2 Comments

so if you dont disable 'guest' middleware validator won't automatically return a http response with 422, which should be catched by your ajax? That would be really weird if solution was disabling a middleware that has nothing to do with validating?
It's weird indeed, but I think it has to do with some redirect from the middleware

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.