watson/aggregate

Extend Laravel's query builder with additional relation aggregates.
161,408 60
Install
composer require watson/aggregate
Latest Version:5.4.0
PHP:^8.1
License:MIT
Last Updated:Mar 28, 2026
Links: GitHub  ·  Packagist
Maintainer: dwightwatson

Aggregate

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).

Installation

You can install the package via Composer:

composer require watson/aggregate

Usage

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) {
    $order->products_sum;
});

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) {
    $order->products_count;

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

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

    $order->products_max;
});

Testing

vendor/bin/phpunit

Related Packages

spatie/laravel-sluggable

Generate slugs when saving Eloquent models

14,760,802 1,557
kodeine/laravel-acl

Light-weight role-based permissions for Laravel 5 built in Auth system.

365,109 775
hootlex/laravel-friendships

This package gives Eloquent models the ability to manage their friendships.

128,287 698
spatie/laravel-translatable

A trait to make an Eloquent model hold translations

30,991,284 2,461

Version History

Version Released PHP Laravel License
5.4.0 ^8.1 ^10.0|^11.0|^12.0|^13.0 MIT
5.3.0 ^8.1 ^10.0|^11.0|^12.0 MIT
5.2.0 ^8.1 ^10.0|^11.0 MIT
5.1.0 ^8.1 ^10.0 MIT
5.0.0 ^8.0 ~9.0 MIT