NewWe open-sourced 50+ Laravel packages
Custom AI apps, agents and automation — Roundly ConsultingRoundly
All packages
Metrics for Laravel

Aggregate helpers

Inside calculate() — or as the first fluent call on an inline builder — pick an aggregate over an Eloquent query. $column is the aggregated column; $dateColumn is the column the date range filters on, and defaults to the model’s qualified created_at:

// Value & Progress
count(Builder $query, ?string $column = null, ?string $dateColumn = null)
// average(), sum(), max(), min() — same signature

// Trend — $column is required
count(Builder $query, string $column, ?string $dateColumn = null)
// average(), sum(), max(), min() — same signature

// Partition
count(Builder $query, string $groupBy, ?string $valueColumn = null, ?string $dateColumn = null)
// average(), sum(), max(), min() — same signature
  • Value and Progress — count() defaults $column to the model’s primary key.
  • Trend — $column is required: it is the value aggregated over time.
  • Partition — $groupBy is the grouping column. Without a $valueColumn, count() counts rows — so the NULL group (keyed '') reports its real size — and the other aggregates use $groupBy.
  • With the ALL range no date filter is applied, so $dateColumn is unused.

Examples

use App\Models\Order;
use RoundlyConsulting\Metrics\Facades\Metrics;

// Average paid order value — any Eloquent constraint narrows the metric
Metrics::value()->average(Order::query()->where('status', 'paid'), 'total');

// Filter the period on a different date column than created_at
Metrics::value()->sum(Order::query(), 'total', 'paid_at')->range('MTD');

// Largest single order per day this month
Metrics::trend()->max(Order::query(), 'total')->daily()->range('MTD');

// Revenue per country — group by one column, sum another
Metrics::partition()->sum(Order::query(), 'country', 'total');

Scopes and constraints

Aggregates run against your query with its global scopes applied, so soft deletes and other constraints are respected. Any where() you add to the builder narrows the metric — point it at the same query your app already trusts.

Calling toArray() on an inline builder before choosing an aggregate throws IncompleteMetricException.

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 crypto

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