'Customizing Laravel validation JSON message format - Laravel
I'm trying to figure out how to customize the Form requests to validate
By default Laravel gives a good enough JSON format for validation errors but what if we want to customize it?
{
"message": "The given data was invalid.",
"errors": {
"email": [
"Please enter email address."
],
"password": [
"Please enter password."
]
}
}
for a particular project, we decided to change the format to this.
{
"success": false,
"errors": [
{
"email": "Please enter an email address."
},
{
"password": "Please enter a password."
}
]
}
Any help would be great.
Regards.
Solution 1:[1]
Please try the following.
public function render($request, Throwable $e)
{
if ($e instanceof ValidationException) {
// Custom response
$response = [
'success' => false,
'error' => $e->errors()
];
return response()->json($response, 422);
}
return parent::render($request, $e);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Karl Hill |