Camkode
Camkode

How to sum multiple colums in Laravel collection

Posted by Kosal

How to sum multiple colums in Laravel collection

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.

1. reduce()

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;
Output:
{
	"price": 57,
	"discount": 20
}

2. pipe()

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;
Output:
{
	"price": 57,
	"discount": 20
}

I hope it can help you...

Reference: Laravel Collection