I have this Array of objects where I wanna sum up the quantity having the same barcode. Am using Laravel if you can give me a eloquent solution that will be great.
[
{
"id": 1,
"barcode": "555",
"description": "pencil",
"quantity": "3",
},
{
"id": 2,
"barcode": "555",
"description": "pencil",
"quantity": "1",
},
{
"id": 3,
"barcode": "123",
"description": "paper",
"quantity": "1",
},
{
"id": 4,
"barcode": "123",
"description": "paper",
"quantity": "8",
},
]
desired output
[
{
"id": 1,
"barcode": "555",
"description": "pencil",
"qty": "4",
},
{
"id": 2,
"barcode": "123",
"description": "pencil",
"qty": "9",
}
]
thanks
You can use the collection's groupBy and map (or flatMap) methods.
$collection
->groupBy('barcode')
->map(fn ($group, $key) => [
'id' => $group->first()['id'],
'barcode' => $group->first()['barcode'],
'description' => $group->first()['description'],
'qty' => $group->sum('qty'),
])
->values();