Updated June 2026. Tested on Laravel 13 and PHP 8.4.
Sometimes you do not want the records themselves, you want a number about them. How many active products, the highest price, the average rating. Eloquent gives you aggregate methods that return that single value straight from the database, without pulling the rows into PHP first.
The methods are count, max, min, sum and avg. Build your query as usual, then call one of them at the end instead of get.
use App\Models\Product;
$count = Product::where('is_active', true)->count();
$max = Product::where('is_active', true)->max('price');
$min = Product::where('is_active', true)->min('price');
$sum = Product::where('is_active', true)->sum('price');
$avg = Product::where('is_active', true)->avg('price');
count takes no column. The other four take the column you are measuring.
Why this matters for performance
It is tempting to write Product::where('is_active', true)->get()->count(). That works, but it is wasteful. It pulls every matching row out of the database, builds a model for each one, then counts them in PHP. Calling ->count() on the query instead runs a single select count(*) and brings back just the number. The bigger the table, the bigger the difference.
The same holds for the others. ->sum('price') adds the column up in the database. Loading the rows to add them yourself would move all that data into memory for nothing.
Grouping
When you want an aggregate per group rather than one overall number, combine groupBy with selectRaw.
$totals = Product::selectRaw('category_id, sum(price) as total')
->groupBy('category_id')
->get();
That gives you one row per category with its total, computed entirely in the database.
So whenever you need a number about your data rather than the data itself, reach for an aggregate method and let the database do the work. Questions welcome in the comments.
All comments ()
No comments yet
Be the first to leave a comment on this post.