Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant code to convert Laravel $validation->messages() to array of objects

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.

like image 476
Evgeniy Avatar asked Aug 31 '25 18:08

Evgeniy


2 Answers

$validation->messages()->all();
like image 61
Martin Bean Avatar answered Sep 02 '25 06:09

Martin Bean


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 :)

like image 39
Evgeniy Avatar answered Sep 02 '25 08:09

Evgeniy