Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Calculating Totals with Laravel Collection Aggregates

After PHP retrieves records into a Laravel collection, the collection's sum(), avg(), min(), and max() methods calculate common summaries without a hand-written loop. A Laravel collection is an object for working with a group of items, such as database records or arrays. These aggregate methods each return one summary. They can aggregate each item directly, use a field name, or use a callback, which is a function that calculates a value from each item.

A field name makes a simple calculation easy to read: sum('pages') shows which values the code adds. A callback handles values the code must calculate first. The examples below follow Laravel 13.x behavior. Check the documentation for the version installed in your project.

Choose a field or callback

For a collection of numbers, call an aggregate without an argument. For records or arrays, pass a field name to select a value from each item. You can also pass a callback to calculate the value the aggregate uses. The Laravel collection documentation shows these forms.

$books = collect([
    ['title' => 'Book A', 'pages' => 176],
    ['title' => 'Book B', 'pages' => 1096],
]);

$totalPages = $books->sum('pages'); // 1272

Use a callback when the value does not exist as a single field. Here, each order’s total comes from multiplying its quantity by its unit price:

$orders = collect([
    ['quantity' => 2, 'unit_price' => 12],
    ['quantity' => 1, 'unit_price' => 30],
    ['quantity' => 3, 'unit_price' => 8],
]);

$orderTotal = fn (array $order) =>
    $order['quantity'] * $order['unit_price'];

$totalSales = $orders->sum($orderTotal); // 78

This callback makes the calculation explicit and reusable in each aggregate call. For simple property totals, Laravel also documents the higher-order form $users->sum->votes; a field name or callback may be easier to follow when readers are unfamiliar with that syntax.

Calculate averages and extremes

avg() returns the arithmetic mean of the selected values. For the order totals above, avg() calculates their mean:

$averageOrder = $orders->avg($orderTotal);

Laravel also provides average() as an alias for avg(). In the 13.x implementation, avg() excludes selected values that are null from the count it uses as the denominator. Because the method returns a nullable value, handle collections with no non-null values. Check the Laravel 13.x implementation if nullable fields affect your calculation.

Use min() and max() to get the lowest and highest selected values. Using the same callback, min() returns 24 and max() returns 30:

$smallestOrder = $orders->min($orderTotal); // 24
$largestOrder = $orders->max($orderTotal);  // 30

These methods return the extreme value, rather than the whole record that produced it. If the selected field or callback result can be null, define how the calculation should treat missing values and test that behavior. The 13.x implementation excludes nulls in its minimum and maximum logic.

Use aggregates when the calculation is the point

A collection aggregate often reads more clearly than a loop when the code asks one direct question about a collection. Compare the page total:

$totalPages = $books->sum('pages');

with the loop that performs the same calculation:

$totalPages = 0;

foreach ($books as $book) {
    $totalPages += $book['pages'];
}

Both approaches work. The aggregate names the statistic and the field in one expression; the loop spells out the accumulator and each update. Use the aggregate when that direct expression makes the code easier to understand.

Separate calls also make a compact summary of the sample orders:

$summary = [
    'sales' => $orders->sum($orderTotal),
    'average_order' => $orders->avg($orderTotal),
    'smallest_order' => $orders->min($orderTotal),
    'largest_order' => $orders->max($orderTotal),
];

Each call expresses one requested statistic. The collection runs each aggregate separately. A single loop may suit code that calculates several statistics in one pass or applies more involved rules. The loop can update the sum and count while also tracking the minimum and maximum. The code must manage all four values as they change. Laravel’s documentation and implementation describe how the methods work, but do not establish that they run faster than loops.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *