I have a collection of objects extracted from my database using the Laravel Rloquent ORM (I do not use Laravel only integrated Eloquent in my own Framework). I used the transform method to iterate over the collection and unserializeone of the columns of each record, then collapsed the collection to put all unserialized objects into one array.
Here is the logic:
$orders = Order::where('user', $user)->orderBy('id', 'desc')->get();
$orders->transform(function($order, $key) {
$order->cart = unserialize($order->cart);
$items = $order->cart->items;
return $items;
});
$collapsed = $orders->collapse();
And the conclusion:
[
{
"qty": "2",
"price": 200,
"item": {
"id": 1,
"title": "Black Hoodie",
"img": "https://s3.amazonaws.com/bucket/black-hoodie.jpg",
"description": "Plain Black Hoodie.",
"price": 100
}
},
{
"qty": "2",
"price": 200,
"item": {
"id": 2,
"title": "Green Hoodie",
"img": "https://s3.amazonaws.com/bucket/green-hoodie.jpg",
"description": "Plain Green Hoodie.",
"price": 100
}
},
{
"qty": 1,
"price": 100,
"item": {
"id": 2,
"title": "Green Hoodie",
"img": "https://s3.amazonaws.com/bucket/green-hoodie.jpg",
"description": "Plain Green Hoodie.",
"price": 100
}
},
{
"qty": 1,
"price": 100,
"item": {
"id": 1,
"title": "Black Hoodie",
"img": "https://s3.amazonaws.com/bucket/black-hoodie.jpg",
"description": "Plain Black Hoodie.",
"price": 100
}
}
]
Now I want to do the following: to combine all the same objects in this array, ideally, by their value "item":{"id"}, into one object - adding their properties qtyand pricetogether leaving the itemproperty the same.
My desired result will be
[
{
"qty": "3",
"price": 300,
"item": {
"id": 1,
"title": "Black Hoodie",
"img": "https://s3.amazonaws.com/bucket/black-hoodie.jpg",
"description": "Plain Black Hoodie.",
"price": 100
}
},
{
"qty": "3",
"price": 300,
"item": {
"id": 2,
"title": "Green Hoodie",
"img": "https://s3.amazonaws.com/bucket/green-hoodie.jpg",
"description": "Plain Green Hoodie.",
"price": 100
}
}
]
Eloquent TONS , , , , .