Kosal Ang
Thu Jul 21 2022
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:
1$products = [ 2 ['name' => 'Product 1', 'price' => 12, 'discount' => 7,], 3 ['name' => 'Product 2', 'price' => 20, 'discount' => 5], 4 ['name' => 'Product 3', 'price' => 25, 'discount' => 8], 5]; 6 7$result = collect($products)->reduce(function ($total, $item) { 8 $total['price'] += $item['price']; 9 $total['discount'] += $item['discount']; 10 return $total; 11}, ['price' => 0, 'discount' => 0]); 12 13return $result; 14
1{ 2 "price": 57, 3 "discount": 20 4} 5
The pipe
method passes the collection to the given closure and returns the result of the executed closure:
1$products = [ 2 ['name' => 'Product 1', 'price' => 12, 'discount' => 7,], 3 ['name' => 'Product 2', 'price' => 20, 'discount' => 5], 4 ['name' => 'Product 3', 'price' => 25, 'discount' => 8], 5]; 6 7$result = collect($products)->pipe(function ($collection) { 8 return collect([ 9 'price' => $collection->sum('price'), 10 'discount' => $collection->sum('discount'), 11 ]); 12}); 13 14return $result; 15
1{ 2 "price": 57, 3 "discount": 20 4} 5
I hope it can help you...
Reference: Laravel Collection
Routing is a crucial aspect of any web application, determining how URLs are mapped to controllers and actions
Learn how to efficiently organize and analyze data with Laravel's Eloquent ORM. This tutorial demonstrates grouping data by relationships, using a practical example of aggregating sales data by vendor. Discover the simplicity and power of Laravel for complex data operations.