Usually, when validating form requests in Laravel, we can access the errors using $validation->messages(). For example:
object(Illuminate\Support\MessageBag)#184 (2) { ["messages":protected]=> array(2) { ["email"]=> array(1) { [0]=> string(40) "The email must be a valid email address." } ["password"]=> array(2) { [0]=> string(41) "The password confirmation does not match." [1]=> string(43) "The password must be at least 6 characters." } } ["format":protected]=> string(8) ":message" }.
Is there some elegant way to convert the object MessageBag to a sample array, such as:
[
object({"email" => "The email must be a valid email address."}),
object({"password" => "The password confirmation does not match."})
...
]
PS: If in the MessageBag, any field has more then one item, I would like only the first item in the resulting array of objects.
Thanks in advance.
$validation->messages()->all();
Ok, something like this
$response = [];
foreach ($validator->messages()->toArray() as $key => $value) {
$obj = new \stdClass();
$obj->name = $key;
$obj->message = $value[0];
array_push($response, $obj);
}
It is not elegant but I do not see another way :)
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