Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Error Field Names in Laravel Ajax Request Validation

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

enter image description here

How can i reach field names ? I need a has method like in normal requests.

like image 673
Cihan Küsmez Avatar asked Oct 24 '25 19:10

Cihan Küsmez


1 Answers

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."
        ]
    }
}
like image 174
Peter Kota Avatar answered Oct 26 '25 08:10

Peter Kota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!