Sys32's avatar
Level 3

Overwrite default validation return

I am building an API, and the response from validation of the incoming request does not return it the way I would want.

It may be Json, however I need to add a message stating its an error.

Change from

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

to

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

Is this possible?

0 likes
2 replies
ejdelmonico's avatar

For forms, you have to overide the messages method and it should return an array of attributes-rule pairs for the error message to be customized.

public function messages()
{
    return [
        'username.required' => 'The username field is required.',
        'password.required' => 'The password field is required.',
    ];
}

or

$messages = [
    'email.required' => 'We need to know your e-mail address!',
];
Sys32's avatar
Sys32
OP
Best Answer
Level 3

Here is what I did, bound the validator object to a variable. Got the errors, got the errors in array format, then simply pushed the array to json format and added it to messages.

$validator = Validator::make($request->all(), [
    'server_id' => 'required|integer|exists:servers,id',
    'username' => 'required|between:6,20|unique:databases',
    'password' => 'required|between:10,20',
]);

$errors = $validator->errors();
$errors = $errors->all();

if ($errors) {
    return response()->json([
        "status" => "error",
        "message" => $errors,
    ]); 
}

Please or to participate in this conversation.