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
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.