watson / aggregate
Extend Laravel's query builder with additional relation aggregates.
Installs: 113 506
Dependents: 4
Suggesters: 0
Security: 0
Stars: 62
Watchers: 4
Forks: 10
Open Issues: 0
Requires
- php: ^8.1
- illuminate/database: ^10.0|^11.0
Requires (Dev)
- mockery/mockery: ^1.4.4
- orchestra/testbench: ^8.0|^9.0
- phpunit/phpunit: ^9.5.10|^10.5
README
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