Laravel 5 Validation - Return as json / ajax Laravel 5 Validation - Return as json / ajax laravel laravel

Laravel 5 Validation - Return as json / ajax


You can use $validator->messages() that returns an array which contains all the information about the validator, including errors. The json function takes the array and encodes it as a json string.

if ($validator->fails()) {        return response()->json($validator->messages(), Response::HTTP_BAD_REQUEST);}

Note: In case of validation errors, It's better not to return response code 200. You can use other status codes like 400 or Response::HTTP_BAD_REQUEST


In Laravel 5.4 the validate() method can automatically detect if your request is an AJAX request, and send the validator response accordingly.

See the documentation here

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

So you could simply do the following:

Validator::make($request->all(), [    'about' => 'min:1'])->validate();


You can also tell Laravel you want a JSON response. Add this header to your request:

'Accept: application/json'

And Laravel will return a JSON response.