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.
array_map(function ($item) { if (is_array($item)) { return reset($item); } return $item; }, $m->getMessages());(In fact, because we know the messages are always an array you could remove theis_arrayconditional if you want to.)$validation->messages()->toArray()? You used to be able to do$validation->messages()->toJson(), so I am assuming toArray() would also work.