# Metrics

> Compute counts, totals, breakdowns, trends and top lists over the rows of a resource, with ranges, time zones and a result cache.

A metric computes one result over the rows of a search: a count, a total, a breakdown, a series over time. It runs on the [perimeter](/resources/perimeter) of the resource and on the search that the client sends, so a dashboard reads the same rows as the list next to it.

## Defining a metric

Generate a metric with `rest:metric`. The class is written in `app/Rest/Metrics`:

```bash
php artisan rest:metric TotalRevenue --type=value
php artisan rest:metric OrdersByStatus --type=partition --group-by=status
```

Five built-in types compute the usual results in one query: `Value`, `Partition`, `Progress`, `Trend` and `Table`. Extend one and call its helpers in `calculate()`:

```php
use Illuminate\Database\Eloquent\Builder;
use Lomkit\Rest\Metrics\Value;
use Lomkit\Rest\Metrics\ValueResult;

class TotalRevenue extends Value
{
    public function calculate(Builder $query): ValueResult
    {
        return $this->sum($query, 'price', 'placed_at');
    }

    public function ranges(): array
    {
        return [30 => '30 days', 90 => '90 days'];
    }
}
```

List it by its class in the `metrics()` method of the resource:

```php
public function metrics(): array
{
    return [TotalRevenue::class];
}
```

- `calculate()` receives an Eloquent query on the model: the perimeter of the resource, then the `search` of the request, without order, selected columns or limit.
- The helpers read the fields that the resource declares. A sum, an average, a min, a max, a median or a percentile needs a `Number` or `Integer` field, a date column a `Date` or `DateTime` field, and a group column a `Text`, `Enum`, `Integer` or `Boolean` field. Another field throws `Lomkit\Rest\Exceptions\InvalidMetricException` when the metric runs.
- The metric is named after its class, without a `Metric` suffix: `TotalRevenue` gives `Total Revenue` and the key `total-revenue`.
- Registering the routes builds no class. The container builds the metric only when it is used: a request for its key, `/details`, the [OpenAPI document](/digging-deeper/openapi) or `rest:check`. Its constructor can inject services.
- `rest:metric` prints the line to add: `List it in the metrics() of a resource by its class: TotalRevenue::class.`

### Configuring a metric

A metric carries its own configuration in its properties:

```php
use Lomkit\Rest\Metrics\CacheScope;
use Lomkit\Rest\Metrics\Partition;

class OrdersByStatus extends Partition
{
    public ?int $limit = 5;

    public ?int $cacheFor = 600;

    public CacheScope $cacheScope = CacheScope::Global;

    public array $middleware = ['throttle:reports'];
}
```

<table>
<thead>
  <tr>
    <th>
      Property
    </th>
    
    <th>
      Sets
    </th>
    
    <th>
      Section
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        $name
      </code>
      
      , <code>
        $uriKey
      </code>
    </td>
    
    <td>
      the name in <code>
        /details
      </code>
      
       and the key of the route
    </td>
    
    <td>
      <a href="#route-key-and-name">
        Route key and name
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $withoutSearching
      </code>
    </td>
    
    <td>
      skips the resource's <code>
        searching()
      </code>
      
       event
    </td>
    
    <td>
      <a href="#requesting-a-metric">
        Requesting a metric
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $weekStartsOn
      </code>
    </td>
    
    <td>
      the first day of a week in a trend
    </td>
    
    <td>
      <a href="#trend">
        Trend
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $limit
      </code>
    </td>
    
    <td>
      the parts, splits or rows that the result keeps
    </td>
    
    <td>
      <a href="#partition">
        Partition
      </a>
      
      , <a href="#table">
        Table
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $cacheFor
      </code>
      
      , <code>
        $cacheScope
      </code>
    </td>
    
    <td>
      the result cache
    </td>
    
    <td>
      <a href="#caching-a-result">
        Caching a result
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $middleware
      </code>
      
      , <code>
        $withoutMiddleware
      </code>
    </td>
    
    <td>
      the middleware of the route
    </td>
    
    <td>
      <a href="#abilities-and-routes">
        Abilities and routes
      </a>
    </td>
  </tr>
</tbody>
</table>

An instance sets the same values with `->withoutSearching()`, `->weekStartsOn()`, `->limit()`, `->cacheFor()`, `->cacheScope()`, `->middleware()` and `->withoutMiddleware()`. List an instance, such as `TotalRevenue::make()->cacheFor(60)`, for a metric reused with other settings in several resources.

### Route key and name

`$uriKey` sets the route key apart from the name:

```php
class OpenTicketCount extends Value
{
    public ?string $uriKey = 'open';
}
```

The metric gets `POST /api/tickets/metrics/open`, named `tickets.metric.open`, and `/details` keeps the name `Open Ticket Count`. Without `$uriKey`, the key comes from `$name`, else from the class name.

## Requesting a metric

Each metric gets the route `POST /{resource}/metrics/{uriKey}`, named `{name}.metric.{uriKey}`:

```http
POST /api/orders/metrics/total-revenue
```

```json
{}
```

```json
{"data": {"type": "value", "value": 52.0, "previous": 37.25}}
```

The body takes three optional keys:

<table>
<thead>
  <tr>
    <th>
      Key
    </th>
    
    <th>
      Value
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        search
      </code>
    </td>
    
    <td>
      <code>
        text
      </code>
      
      , <code>
        trashed
      </code>
      
      , <code>
        filters
      </code>
      
      , <code>
        scopes
      </code>
      
       and <code>
        instructions
      </code>
      
       of a <a href="/search/overview">
        search
      </a>
      
      . <code>
        sorts
      </code>
      
      , <code>
        selects
      </code>
      
      , <code>
        includes
      </code>
      
      , <code>
        aggregates
      </code>
      
      , <code>
        gates
      </code>
      
      , <code>
        limit
      </code>
      
       and <code>
        page
      </code>
      
       are a <code>
        422
      </code>
      
      , such as <code>
        The search.limit field is prohibited.
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        range
      </code>
    </td>
    
    <td>
      a key of <code>
        ranges()
      </code>
      
      . The first range applies when the request sends none.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        timezone
      </code>
    </td>
    
    <td>
      a time zone name, such as <code>
        Europe/Paris
      </code>
      
      . <code>
        config('app.timezone')
      </code>
      
       applies when the request sends none.
    </td>
  </tr>
</tbody>
</table>

```json
{"range": 90, "search": {"filters": [{"field": "status", "value": "paid"}]}}
```

- A `range` that the metric does not declare is a `422`, and so is `range` on a metric without ranges.
- An unknown zone, or an offset such as `+01:00`, is a `422`.
- An unknown metric answers `404` to a user allowed `viewAny` on the resource, and `403` to the others.
- The search runs the resource's `searching()` event first. A metric that must skip it declares `public bool $withoutSearching = true;`, or `->withoutSearching()` on an instance.
- Floats keep their fraction in the response: `52.0`, not `52`.

## Value

A `Value` gives one number, and the same number over the previous period when the metric declares ranges. A range key counts days.

<table>
<thead>
  <tr>
    <th>
      Helper
    </th>
    
    <th>
      Computes
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        count($query, $dateColumn = 'created_at')
      </code>
    </td>
    
    <td>
      the number of rows
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        sum($query, $column, $dateColumn = 'created_at')
      </code>
    </td>
    
    <td>
      the total of a column
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        average()
      </code>
      
      , <code>
        min()
      </code>
      
      , <code>
        max()
      </code>
      
      , <code>
        median()
      </code>
    </td>
    
    <td>
      with the parameters of <code>
        sum()
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        percentile($query, $column, $percentile, $dateColumn = 'created_at')
      </code>
    </td>
    
    <td>
      the value under which a share of the values falls
    </td>
  </tr>
</tbody>
</table>

With ranges, `value` covers the last N days and `previous` the N days before. Without ranges, `value` covers every row, `previous` is `null` and the date column is not read.

- A count is an integer. A sum, min or max is an integer for an `Integer` field and a float for a `Number` field. An average, a median or a percentile is a float.
- Over no row, a count and a sum give `0`, the others `null`.

## Partition

A `Partition` gives one part per value of a column:

```php
use Lomkit\Rest\Metrics\Partition;
use Lomkit\Rest\Metrics\PartitionResult;

class OrdersByStatus extends Partition
{
    public function calculate(Builder $query): PartitionResult
    {
        return $this->count($query, 'status');
    }
}
```

```json
{"data": {"type": "partition", "parts": [{"key": "paid", "label": "Paid", "value": 5}, {"key": "pending", "label": "Pending", "value": 1}, {"key": null, "label": null, "value": 1}], "other": null}}
```

- Helpers: `count($query, $groupBy, $dateColumn = null)`, `sum($query, $column, $groupBy, $dateColumn = null)`, `average()`, `min()`, `max()` and `median()` with the parameters of `sum()`, and `percentile($query, $column, $percentile, $groupBy, $dateColumn = null)`.
- Each part holds the stored value as `key` and a `label`: the enum case name for an `Enum` field, the key as text otherwise. The rows without a value form the part whose key is `null`.
- Parts are sorted by value, largest first, then by key.
- `public ?int $limit = 5;`, or `->limit(5)` on an instance, keeps the 5 largest parts and folds the others into `other`: `{"label": "Other", "value": 3}`. `other` is `null` when nothing is folded.
- Without `limit()`, a partition keeps its `rest.limits.sizes.groups` largest parts, `100` by default and at least `1`. `limit()` raises or lowers that number for one metric. See [Limits](/resources/limits#metric-groups).
- `->labels(['paid' => 'Payée'], other: 'Autre')` on the result renames parts and `other`.

### Comparing with the previous period

With a named `dateColumn` and `ranges()`, a partition reads the last N days and gives each part and `other` a `previous` value over the N days before:

```php
return $this->sum($query, 'amount', 'currency', dateColumn: 'paid_at');
```

```json
{"data": {"type": "partition", "parts": [{"key": "EUR", "label": "EUR", "value": 18240.5, "previous": 16002.0}, {"key": "USD", "label": "USD", "value": 9100.0, "previous": 9875.25}], "other": null}}
```

A key without rows in one of the two periods gets `null` there.

## Progress

A `Progress` gives a value and its target:

```php
return $this->sum($query, 'price', target: 100000);
```

```json
{"data": {"type": "progress", "value": 52000.0, "target": 100000.0}}
```

The helpers are `count($query, $target, $dateColumn = 'created_at')`, `sum($query, $column, $target, $dateColumn = 'created_at')`, `average()`, `min()` and `max()`. The target can come from the request: `target: $this->request()->user()->monthly_goal`.

## Trend

A `Trend` gives one value per day, week or month. A trend declares `ranges()`, and a range key counts periods, the current one included:

```php
use Lomkit\Rest\Metrics\Trend;
use Lomkit\Rest\Metrics\TrendResult;

class RevenuePerMonth extends Trend
{
    public function calculate(Builder $query): TrendResult
    {
        return $this->sumByMonths($query, 'price', 'placed_at');
    }

    public function ranges(): array
    {
        return [3 => '3 months', 6 => '6 months', 12 => '12 months'];
    }
}
```

```json
{"range": 6}
```

```json
{
  "data": {
    "type": "trend",
    "series": [
      {"label": "2026-06", "value": 0.0},
      {"label": "2026-07", "value": 0.0},
      {"label": "2026-08", "value": 0.0},
      {"label": "2026-09", "value": 0.0},
      {"label": "2026-10", "value": 20.0},
      {"label": "2026-11", "value": 43.5}
    ]
  }
}
```

- Helpers: `countByDays($query, $dateColumn = 'created_at', $splitBy = null)`, `countByWeeks()`, `countByMonths()`, then `sumBy...`, `averageBy...`, `minBy...`, `maxBy...` and `medianBy...` with `($query, $column, $dateColumn = 'created_at', $splitBy = null)`, and `percentileBy...` with `($query, $column, $percentile, $dateColumn = 'created_at', $splitBy = null)`.
- Labels: a day `2026-11-07`, a week the date of its first day, a month `2026-11`. Every period of the range is in the series, oldest first. A period without rows is `0` for a count or a sum, `null` for the others.
- Weeks start on Monday. `public int $weekStartsOn = Carbon::SUNDAY;`, or `->weekStartsOn(Carbon::SUNDAY)` on an instance, starts them on another day.
- `timezone` counts the periods in that zone, changes of offset included.

### Splitting a trend

`splitBy` adds one series per value of a column, here over the first range, 3 months:

```php
return $this->countByMonths($query, 'placed_at', splitBy: 'status');
```

```json
{
  "data": {
    "type": "trend",
    "series": [{"label": "2026-09", "value": 0}, {"label": "2026-10", "value": 1}, {"label": "2026-11", "value": 4}],
    "splits": [
      {"key": "paid", "label": "Paid", "series": [{"label": "2026-09", "value": 0}, {"label": "2026-10", "value": 0}, {"label": "2026-11", "value": 2}]},
      {"key": "pending", "label": "Pending", "series": [{"label": "2026-09", "value": 0}, {"label": "2026-10", "value": 1}, {"label": "2026-11", "value": 1}]},
      {"key": null, "label": null, "series": [{"label": "2026-09", "value": 0}, {"label": "2026-10", "value": 0}, {"label": "2026-11", "value": 1}]}
    ],
    "other": null
  }
}
```

- Each split holds `key`, `label` and its `series`, labelled as the parts of a [partition](#partition). The splits come in the order of their key, the `null` key last.
- `public ?int $limit = 5;`, or `->limit(5)` on an instance, keeps the 5 splits with the largest total over the range and folds the others into `other`: an object with `label`, `Other`, and a `series` that holds their values per period. `other` is `null` when nothing is folded.
- Without `limit()`, a trend keeps its `rest.limits.sizes.groups` largest splits, `100` by default, as a [partition](#partition) keeps its parts.

## Table

A `Table` gives the top rows of a grouped aggregate, one column per count, sum, average, min, max, median or percentile:

```php
use Lomkit\Rest\Metrics\Table;
use Lomkit\Rest\Metrics\TableColumn;
use Lomkit\Rest\Metrics\TableResult;

class TopCustomers extends Table
{
    public int $limit = 5;

    public function calculate(Builder $query): TableResult
    {
        return $this->rows($query, 'customer', [
            'orders' => TableColumn::count(),
            'revenue' => TableColumn::sum('price'),
            'basket' => TableColumn::average('price')->label('Average basket'),
        ], orderBy: 'revenue', dateColumn: 'placed_at');
    }

    public function ranges(): array
    {
        return [30 => '30 days', 365 => '365 days'];
    }
}
```

```json
{"data": {"type": "table", "columns": [{"name": "orders", "label": "Orders", "aggregate": "count"}, {"name": "revenue", "label": "Revenue", "aggregate": "sum"}, {"name": "basket", "label": "Average basket", "aggregate": "average"}], "rows": [{"key": "acme", "label": "acme", "values": {"orders": 2, "revenue": 150.0, "basket": 75.0}}]}}
```

- `rows($query, $groupBy, $columns, $orderBy = null, $direction = 'desc', $dateColumn = 'created_at')`. A column name starts with a lowercase letter and holds letters, digits and underscores.
- `TableColumn::count()`, `sum($field)`, `average($field)`, `min($field)`, `max($field)`, `median($field)` and `percentile($field, $percentile)`. `->label()` names a column, else its name in words.
- The rows are ordered by `$orderBy`, the first column by default, largest first. `'asc'` puts the smallest first.
- `$limit` keeps from 1 to 100 rows, 10 by default. `->limit(5)` sets it on an instance.
- `->labels([...])` on the result renames rows. For labels stored elsewhere, read them for `$table->keys()`.

## Median and percentile

`median()` and `percentile()` work on `Value`, `Partition`, `Trend` (`medianByMonths()`, `percentileByMonths()`) and `Table` (`TableColumn::median()`, `TableColumn::percentile()`):

```php
return $this->percentile($query, 'resolution_minutes', 0.9, 'closed_at');
```

- The percentile is a number from 0 to 1. Another value throws `InvalidMetricException` when the metric runs.
- The result is interpolated between the two nearest rows, as PostgreSQL `percentile_cont()` does. Rows without a value are left out.
- The database sorts the rows of each group: index the column on a large table.
- SQLite, MySQL, MariaDB and PostgreSQL are supported.

## Your own metric

A metric of your own extends `Lomkit\Rest\Metrics\Metric`, names its type in `type()` and returns a `MetricResult`:

```php
use Lomkit\Rest\Metrics\Metric;
use Lomkit\Rest\Metrics\MetricResult;

class TicketBacklog extends Metric
{
    public function type(): string
    {
        return 'gauge';
    }

    public function calculate(Builder $query): MetricResult
    {
        return new Gauge($query->where('status', 'open')->count(), 500);
    }
}

final readonly class Gauge implements MetricResult
{
    public function __construct(private int $value, private int $max) {}

    public function jsonSerialize(): array
    {
        return ['value' => $this->value, 'max' => $this->max];
    }
}
```

```json
{"data": {"type": "gauge", "value": 42, "max": 500}}
```

- `type()` holds lowercase letters, digits and dashes. A result with its own `type` key throws `InvalidMetricException`.
- `$this->range()` gives the selected range, `$this->timezone()` the zone of the request, and `$this->periods($query, 'placed_at', PeriodUnit::Day, 7)` the periods of a series.
- `schema()` describes the result in the [OpenAPI document](/digging-deeper/openapi). It returns a Scramble type, `?Type`, or `null` by default: the document then gives `type` alone.

## Caching a result

The `$cacheFor` property keeps the result between requests, for a number of seconds:

```php
use Lomkit\Rest\Metrics\CacheScope;

class OrdersByStatus extends Partition
{
    public ?int $cacheFor = 600;

    public CacheScope $cacheScope = CacheScope::Global;
}
```

- On an instance, `->cacheFor()` takes seconds, a `DateInterval` or an instant such as `now()->addMinutes(10)`: `TotalRevenue::make()->cacheFor(now()->addMinutes(10))`.
- Each user gets their own result. `public CacheScope $cacheScope = CacheScope::Global;`, or `->cacheScope('global')` on an instance, shares one result between the users whose `perimeterQuery()` compiles to the same SQL and bindings, on the resource and on each resource that the `search` reaches through a relation filter or group: the users of one team share it, another team gets its own.
- The key also holds the resource, the metric and its settings, `$uriKey` included, the `range`, `timezone` and `search` of the request, and the values of `authorizationCacheContext()` on the resource and on each resource that the `search` reaches, with either scope.
- A kept result still runs validation, the abilities, the middleware and `searching()`. It skips the queries of the metric.
- The results go to the store of `authorizations.cache.store`. `Rest::forgetAuthorizationsFor($user)` drops the results of a user, `Rest::forgetAuthorizations()` drops every result, and `authorizations.cache.enabled` set to `false` keeps none. See [Decision cache](/authorization/decision-cache).

<warning>

A global result keys the SQL of `perimeterQuery()` only. A perimeter that also depends on a global scope of the model, or on the tenant of a database per tenant, adds that value to `authorizationCacheContext()`, or the tenants share one result.

</warning>

## Abilities and routes

- A metric checks `viewAny` on the resource, the abilities of the resource's `abilities()` for `Endpoint::Metric`, then the metric's `abilities()`, `['viewAny']` by default. `[]` runs without these checks.
- The `$middleware` and `$withoutMiddleware` properties, or `->middleware()` and `->withoutMiddleware()` on an instance, work as for [actions](/actions-and-metrics/actions#middleware).
- `Rest::resource()` reads `metrics()` when it registers the routes: keep the list the same for every user. `except('metric')` removes the metric routes.
- A metric listed by its class follows the [declaration checks](/actions-and-metrics/actions#declaration-checks) of an action, with `InvalidMetricException`. Registering the routes refuses a class that overrides `name()` or `uriKey()`, an abstract class, `Metric::class` itself and a class that does not extend `Metric`. A built metric whose key or middleware differ from the defaults of its properties throws and does not run.
- The other declaration errors of a metric class, such as a `$weekStartsOn` out of `0` to `6`, throw when it is first built, and `rest:check` reports them.
- Each metric route records its key and middleware, also through `php artisan route:cache`: run it again after you change them, see [Cached routes](/actions-and-metrics/actions#cached-routes).
- The [details](/digging-deeper/details), with `?with=metrics`, list each metric with its `type` and `ranges`.
