Using Laravel Form Request Validation,
How to customize the response format?
For example, it shows error messages as:
{
"password":[
"The password field is required."
],
"password_confirmation":[
"The password confirmation field is required."
]
}
I want to put all error messages into the description property, something like.
{
"status":false,
"description":[
"The password field is required.",
"The password confirmation field is required."
]
}
To pull out all the error messages into an array you would need to do something like this...
$validator = Validator::make($request->all(), [
'password' => 'required',
'password_confirmation' => 'required|same:password',
]);
$messages = $validator->errors()->toArray();
/* ** This will give you something like this **
*
* 'password' => 'The password field is required.',
* 'password_confirmation' => 'The password confirmation field is required.'
*
* **/
// If you want only array values - as your example of description, then use php's array_values() method like this...
$description_arr = array_values($messages);
Thanks hope this will help you..!! For better understanding of Laravel Validations go through its docs - Laravel Validation Docs
It's right below in the doc link that you provided:
You may customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages.
So, put this in your Request:
public function messages()
{
return [
'password.required' => 'The password field is required.',
'password_confirmation.required' => 'The password confirmation field is required.',
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With