sum(), avg() and count()

Aggregate a collection with sum(), avg(), min(), max() and count().

Syntax$collection->sum('key');

Collections include convenient aggregate methods. Each can take a key or callback when working with arrays or objects.

  • sum() — add everything up.
  • avg() — average value.
  • min() / max() — smallest / largest.
  • count() — number of items.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A shopping cart totals the line-item prices with sum('price') to display the order subtotal to the customer.
  • A dashboard widget calculates the average rating of a product by calling avg('rating') on the reviews collection.
  • An analytics report calls count() on a filtered collection to display how many users signed up in the current calendar month.

More examples

Sum a field across collection items

sum() accepts a key name and returns the sum of that field across every item in the collection.

Example · php
$cart = collect([
    ['product' => 'Notebook', 'price' => 12.99],
    ['product' => 'Pen',      'price' =>  1.49],
    ['product' => 'Eraser',   'price' =>  0.79],
]);

$total = $cart->sum('price');
// => 15.27

Average and count in a review system

Calls avg(), count(), min(), and max() on the same collection to compute review statistics without extra queries.

Example · php
$reviews = Review::where('product_id', $product->id)->get();

$avgRating   = $reviews->avg('rating');   // e.g. 4.3
$totalReviews = $reviews->count();         // e.g. 127
$minRating   = $reviews->min('rating');   // 1
$maxRating   = $reviews->max('rating');   // 5

Sum with a callback for computed values

Passes a callback to sum() to compute the line-item subtotal (qty * price) before summing all results.

Example · php
$orders = collect([
    ['qty' => 2, 'price' => 15.00],
    ['qty' => 1, 'price' => 80.00],
    ['qty' => 3, 'price' =>  5.00],
]);

$revenue = $orders->sum(fn($o) => $o['qty'] * $o['price']);
// => 125.00

Discussion

  • Be the first to comment on this lesson.