kajdehoop
kajdehoop

Reputation: 527

Return Laravel validation errors as JSON response

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',
    ]);        
}

Upvotes: 3

Views: 8942

Answers (3)

ali
ali

Reputation: 862

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);
}

Upvotes: 5

kajdehoop
kajdehoop

Reputation: 527

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.

Upvotes: 0

Pol Lluis
Pol Lluis

Reputation: 1162

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

Upvotes: 1

Related Questions