CamKode

How to sum multiple colums in Laravel collection

Avatar of Kosal Ang

Kosal Ang

Thu Jul 21 2022

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:

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
Output:
1{
2	"price": 57,
3	"discount": 20
4}
5

2. pipe()

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
Output:
1{
2	"price": 57,
3	"discount": 20
4}
5

I hope it can help you...

Reference: Laravel Collection

Related Posts

Mastering Laravel Routing: A Comprehensive Guide

Mastering Laravel Routing: A Comprehensive Guide

Routing is a crucial aspect of any web application, determining how URLs are mapped to controllers and actions

Laravel Group by Eloquent Relationship

Laravel Group by Eloquent Relationship

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.

© 2025 CamKode. All rights reserved

FacebookTwitterYouTube