May 30, 2022
7
Level 3
Add property to the validation response
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// Retrieve the validated input...
$validated = $validator->validated();
the exception will be thrown by default like:
{
"message": ".......",
"errors": [
[
"There was an error on....."
]
]
}
my question is how to add other properties in the error validation response like:
{
"message": ".......",
"prop1": ".......",
"prop2": ".......",
"errors": [
[
"There was an error on....."
]
]
}
Level 56
The ValidationException gets serialized on the base Exception handler:
So you either override the invalidJson method on your app's local Exception handler and customize how it is serialized, or you catch the exception and serialize it manually in the spot you need it, for example:
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
try {
// Retrieve the validated input...
$validated = $validator->validated();
} catch (ValidationException $exception) {
return response()->json([
'message' => $exception->getMessage(),
'errors' => $exception->errors(),
'prop1' => 'foo',
'prop2' => 'bar',
], $exception->status);
}
3 likes
Please or to participate in this conversation.