Partitions
A partition groups rows by a column and aggregates each group — the data behind a pie or bar chart. Groups are ordered largest first:
use App\Models\User;
use RoundlyConsulting\Metrics\Facades\Metrics;
Metrics::partition()->count(User::query(), 'plan')->toArray();
// result => ['partitions' => ['pro' => 120.0, 'free' => 80.0, ...]] // largest firstsum(), average(), max() and min() take the same arguments — group by one column and aggregate another:
// Revenue per country this month
Metrics::partition()->sum(Order::query(), 'country', 'total')->range('MTD')->toArray();Top N and the “Other” bucket
Cap a partition to its largest groups and roll the rest into a single bucket, so a chart stays readable:
Metrics::partition()
->count(User::query(), 'country')
->limit(5) // 5 groups + "Other"
->otherLabel('Elsewhere') // optional; defaults to the translatable "Other"
->toArray();
// result => ['partitions' => ['DE' => 120.0, ..., 'Elsewhere' => 35.0]]The bucket is the rest rolled up with the metric’s own aggregate: summed for count() and sum(), the largest value for max(), the smallest for min(), and the average of all the remaining rows (not of the group averages) for average(). A real group whose key equals the bucket’s label is never one of the top N — it joins the bucket, so no group is overwritten.
The default label comes from metrics.partition.other_label (“Other”) and runs through Laravel’s translator; otherLabel() overrides it per metric.
The NULL group
// Without a value column, count() counts rows — the NULL group is keyed ''
Metrics::partition()->count(User::query(), 'plan')->toArray();
// result => ['partitions' => ['pro' => 120.0, 'free' => 80.0, '' => 12.0]]Custom labels
Map raw group keys — a country code, a foreign-key id — to display labels with labelUsing(). Raw keys stay under partitions, and the labels appear under an additional labels key. Labels are resolved on every read, never cached, and the “Other” bucket keeps its own label and is never passed to the resolver:
Metrics::partition()
->count(User::query(), 'country_id')
->labelUsing(fn (int|string $key): string => Country::name($key))
->toArray();
// result => ['partitions' => ['1' => 40.0, ...], 'labels' => ['1' => 'Germany', ...]]Reading the result
- partitions() — group key → value.
- keys() — the raw group keys, regardless of any label resolver.
- labels() — the resolved labels when a resolver is set, otherwise the raw keys.
- values() — the values, in order.
Show your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.