Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel request validation message formatting

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."
   ]
}
like image 963
Dipendra Gurung Avatar asked May 24 '26 11:05

Dipendra Gurung


2 Answers

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

like image 134
Saumya Rastogi Avatar answered May 28 '26 16:05

Saumya Rastogi


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.',
    ];
}
like image 29
pawelmysior Avatar answered May 28 '26 17:05

pawelmysior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!