3

Is there a way to manipulate or change laravel default error messages into JSON response. I am building an API. The current response that I am getting is

{
    "email": [
        "The email has already been taken."
    ],
    "phone": [
        "The phone has already been taken."
    ]
}

I want it to be like this

{
  "errors": [
    {
      "field": "username",
      "message": "The username field is required."
    },
    {
      "field": "password",
      "message": "The password field is required."
    }
  ]
}




$validator = Validator::make($request->all(), [
            'email' => 'required|string|email|max:50|unique:customers',
            'phone' => 'required|string|max:10|min:10|unique:customers',
            'password' => 'required|string|min:6',
        ]);



        if ($validator->fails()) {
           return response()->json($validator->messages(), 200);
        }
8
  • Both code is JSON. Commented Dec 19, 2017 at 10:51
  • I think he wants to put the errors array inside a errors key. Commented Dec 19, 2017 at 10:52
  • @Phiter yes...any solution?? Commented Dec 19, 2017 at 10:53
  • How do you return those errors? Commented Dec 19, 2017 at 10:55
  • @Phiter laravel does that automatically.. I cant even access the array/json that is being returned. Commented Dec 19, 2017 at 10:57

2 Answers 2

2

Extract the errors from the messageBag and format them as you wish:

$errors = [];
foreach($validator->getMessageBag()->toArray() as $key=>$messages) {
    $errors[$key] = $messages[0];
}
return response()->json($errors, 200);
Sign up to request clarification or add additional context in comments.

Comments

2

If you get object as you given first example you can change it by for..in loop like this

var response = {
    "email": [
        "The email has already been taken."
    ],
    "phone": [
        "The phone has already been taken."
    ]
};

var allError = [];
for(let i in response){
   allError.push({
      field: i,
      message: response[i][0]
    });
}
var errors = {errors:allError};
console.log(errors);

You should not change from php/laravel, because then you will not be able to show multiple errors for single input.

Also never change base code which can also work for web. You can't think for only API, It can also be used for web.

3 Comments

Never fix something in local which can be avoided in server.
@Amarnasan : Also never change base code which can also work for web. You can't think for only API, it can also be used for web.
@Amarnasan Neither you nor me completely know the business logic, so I suggest to not change base code from laravel.

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.