Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

maulayyacyber's avatar

How to custom response JSON object validator

i have problem with response validator like this :

{
    "email": [
        "The email field is required."
    ],
    "password": [
        "The password field is required."
    ]
}

im want to like this :

{
    "email": 
        "The email field is required."
    ,
    "password": 
        "The password field is required." 
}

this my validator

$validator = Validator::make($request->all(), [
            'email'    => 'required|email',
            'password' => 'required',
]);

if ($validator->fails()) {
   return response()->json($validator->errors(), 400);
}

everyone can help me ? thanks very much

0 likes
1 reply
thewebartisan7's avatar
Level 14

Because you can have more than one validation messages, for this reasons is an array.

You can on client side loop over each messages and display all or only first.

If you want to handle this on server side, there is several way.

If you know upfront all field name, then you could:

return response()->json([
   'name' => $validator->errors()->first('name'),
   'password' => $validator->errors()->first('password'),
], 400);

Something more generic could be to convert first in a collection, and then you can build new errors array, see https://laravel.com/docs/8.x/collections

For example:

$errors = collect($validator->errors())
              ->reverse()
              ->mapWithKeys(function ($item, $key) {
            return [$key => $item[0]];
        });

But maybe there is better way with collection. I think reverse is required so that first message is not overriden by last.

To get first message on client side would be something like:

// Taking into account that you are using axios which return response in error.response.data
error.response.data.errors[Object.keys(error.response.data.errors)[0]]

And for loops all errors:

                       let errors = error.response.data.errors
                        for (let input in errors) {
                            if (errors.hasOwnProperty(input)) {
                             // First error
                             invalidFeedback.innerHTML = errors[input][0]
                            }
                        }

Please or to participate in this conversation.