2

I try to create an API for the registration form if a user does not fill the required field. The validator show error in object format but i need json response in an array format.

$validator = Validator::make($request->all(), [ 
    'name' => 'required', 
    'mobile' => 'required', 
    'address' => 'required', 
]);
if ($validator->fails()) { 
    return response()->json(['error'=>$validator->errors()], 401);            
}

Current output is

 {
    "error": {
        "name": [
            "The name field is required."
        ],
        "mobile": [
            "The mobile field is required."
        ],
        "address": [
            "The addressfield is required."
        ]
    }
}

Expected output

{
  "error": [
      "The name field is required.",
      "The mobile field is required.",
      "The address field is required."
  ]
}
3
  • What is the issue in accessing the Current output you get? Commented Aug 28, 2018 at 12:42
  • did you finally find a solution? Commented Feb 10, 2019 at 20:54
  • i found a solution and posted it as answer Commented Feb 10, 2019 at 21:25

2 Answers 2

1

Correct answer is this one:

$err = array();

        foreach ($validator->errors()->toArray() as $error)  {
            foreach($error as $sub_error){
                array_push($err, $sub_error);
            }
        }
        return ['errors'=>$err];

the inner foreach is added because maybe more than one validation condition fails for an input( like : password is too short & too weak).

and Mayank Pandeyz's answer for loop won't iterate because until we add toArray() to the end of $validator->errors().

Sign up to request clarification or add additional context in comments.

Comments

0

For getting the expected result, iterate the $validator->errors() using foreach() loop and push all the values in an array and return that array like:

$err = array();
foreach ($validator->errors() as $error)
{
    array_push($err, $error);
}

return response()->json(['error'=>$err], 401);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.