Posted by Kosal
Are you looking for an example of Laravel collection sum multiple columns. you can see Laravel collection sum two columns. I would like to share you with two simple ways to sum multiple column in Laravel. Let's see bellow example Laravel sum multiple columns.
The reduce
method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:
$products = [
['name' => 'Product 1', 'price' => 12, 'discount' => 7,],
['name' => 'Product 2', 'price' => 20, 'discount' => 5],
['name' => 'Product 3', 'price' => 25, 'discount' => 8],
];
$result = collect($products)->reduce(function ($total, $item) {
$total['price'] += $item['price'];
$total['discount'] += $item['discount'];
return $total;
}, ['price' => 0, 'discount' => 0]);
return $result;
{
"price": 57,
"discount": 20
}
The pipe
method passes the collection to the given closure and returns the result of the executed closure:
$products = [
['name' => 'Product 1', 'price' => 12, 'discount' => 7,],
['name' => 'Product 2', 'price' => 20, 'discount' => 5],
['name' => 'Product 3', 'price' => 25, 'discount' => 8],
];
$result = collect($products)->pipe(function ($collection) {
return collect([
'price' => $collection->sum('price'),
'discount' => $collection->sum('discount'),
]);
});
return $result;
{
"price": 57,
"discount": 20
}
I hope it can help you...
Reference: Laravel Collection