Extend Laravel's query builder with additional relation aggregates.

4.1.0 2020-12-16 10:23 UTC

This package is auto-updated.

Last update: 2021-07-16 11:32:40 UTC


Laravel Eloquent allows you to query the count of a relationship using withCount. Aggregate extends Eloquent by adding withSum, withAvg, withMin and withMax.

This is based off the work in laravel/framework#25319 - thanks to Mohammad Sharif Ahrari (@spyp).


You can install the package via Composer:

composer require watson/aggregate


The additional methods will be added by Laravel's autodiscovery feature. You can then use them the same way you already use withCount. See the Laravel documentation for more on how this works.

$orders = Order::withSum('products', 'quantity')->get();

$orders->each(function ($order) {

You can also select multiple aggregates in a single query, as well as alias them.

$orders = Order::withCount('products')->withSum('products as products_price', 'price')->get();

$orders->each(function ($order) {

$orders = Order::withCount('products')->withMax('products', 'price')->get();

$orders->each(function ($order) {