Could we help you? Please click the banners. We are young and desperately need the money
Modern applications rely heavily on reporting, analytics dashboards, aggregated statistics, and data summaries. Laravel’s Eloquent ORM provides several built-in tools to make these operations efficient and expressive — without requiring heavy SQL or complex manual joins. Among the most powerful features are the Eloquent aggregate methods such as withSum, withAvg, withCount, and custom subquery columns.
These features allow you to enrich your models with calculated values directly from the database, offering a clean and high-performance approach to data reporting. In this article, we explore how to use Eloquent aggregates effectively, walk through practical use cases, discuss dependencies and configuration, and compare these techniques against manual SQL or third-party reporting packages.
Performing aggregate calculations such as totals, averages, or counts is common in almost every application. Traditionally, developers might write raw SQL or execute multiple queries to gather the data they need. This approach leads to:
Eloquent aggregates solve these problems by allowing you to attach calculated values directly to your models as part of the query itself, not after execution.
Aggregates are especially useful when you need to return summarized information alongside your models. Common real-world examples include:
Eloquent makes these easy to implement while maintaining readable code.
Eloquent aggregates require no additional setup — they are part of Laravel’s core ORM.
Supported methods include:
These can also be nested, conditional, or combined with subquery columns.
One of the most common aggregate operations is counting related records:
$users = User::withCount('posts')->get();
This adds a new attribute:
$user->posts_count
For multiple counts:
$users = User::withCount(['posts', 'comments'])->get();
Alias the result:
$users = User::withCount(['posts as article_count'])->get();
Suppose a customer has many orders:
$customers = Customer::withSum('orders', 'total_amount')->get();
This adds:
$customer->orders_sum_total_amount
You can also alias it for readability:
$customers = Customer::withSum('orders as total_spent', 'total_amount')->get();
To calculate the average rating of a product:
$products = Product::withAvg('reviews', 'rating')->get();
This adds:
$product->reviews_avg_rating
If no related records exist, the value will be null.
Alias example:
$products = Product::withAvg('reviews as avg_rating', 'rating')->get();
You can add several aggregate functions in a single query:
$products = Product::query()
->withCount('reviews')
->withAvg('reviews as avg_rating', 'rating')
->withSum('sales as revenue', 'amount')
->get();
This returns fully enriched models ready for dashboards or reporting screens.
While withSum(), withAvg(), and withCount() cover most cases, sometimes you need more complex calculations. Laravel supports adding subquery columns directly to your select statement.
$customers = Customer::query()->addSelect([
'last_order_date' => Order::select('created_at')
->whereColumn('customer_id', 'customers.id')
->latest()
->limit(1)
])->get();
$customers = Customer::query()->addSelect([
'current_month_sales' => Order::selectRaw('SUM(total_amount)')
->whereColumn('customer_id', 'customers.id')
->whereMonth('created_at', now()->month)
])->get();
These subquery techniques give you SQL-level power while keeping your queries expressive and readable.
Aggregate queries can include conditional logic.
For example, count only “approved” comments:
$posts = Post::withCount([
'comments' => function ($query) {
$query->where('approved', true);
}
])->get();
Sum only “completed” orders:
$customers = Customer::withSum([
'orders as completed_total' => function ($query) {
$query->where('status', 'completed');
}
],
'total_amount')->get();
Eloquent aggregates are generally fast because they are executed by the database engine. Still, keep in mind:
| Feature | Eloquent Aggregates | Manual SQL | Multiple Queries |
|---|---|---|---|
| Performance | Excellent | Excellent | Poor |
| Readability | High | Low | Medium |
| Maintainability | High | Low | Low |
| Complexity | Low | High | High |
Eloquent aggregates offer a powerful and elegant way to enrich your models with statistical or analytical insights. Whether you are building dashboards, analytics tools, customer summaries, or reporting modules, these aggregate functions allow you to create high-performance, expressive, and maintainable queries with minimal effort.
By leveraging withSum, withAvg, withCount, and subquery columns, you can transform your Laravel application into a clean, fast, and analytics-ready system — all without dropping down to raw SQL.