In Laravel 5.1 Project
I'm getting this Ajax Response As Error
{"errors":["The Address Name field is required.","The Recipient field is required.","The Address field is required."]}
If it is not an Ajax Response in Validation we are using has method to determine which field has mistake.
As you see there exists 3 fields has errors. I'm using twitter-bootstrap and i want to show these errors like in image

How can i reach field names ? I need a has method like in normal requests.
The easiest way is to leverage the MessageBag object of the validator. It gives back the field names on the key. This can be done like this:
// Setup the validator
$rules = array('email' => 'required|email', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
// Validate the input and return correct response
if ($validator->fails())
{
return Response::json(array(
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
), 400); // 400 being the HTTP code for an invalid request.
}
return Response::json(array('success' => true), 200);
This would give you a JSON response like this:
{
"success": false,
"errors": {
"email": [
"The E-mail field is required."
],
"password": [
"The Password field is required."
]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With