PHP code example of syriable / laravel-metrics

1. Go to this page and download the library: Download syriable/laravel-metrics library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

syriable / laravel-metrics example snippets


use Syriable\Metrics\Facades\Metrics;

// One number, compared against the previous 30 days — in a single query.
$result = Metrics::query(Order::class)
    ->sum('total')
    ->range('30d')
    ->compareWithPrevious()
    ->value();

$result->value();                    // 48250.75
$result->comparison()->percentage;   // 12.4
$result->comparison()->direction;    // Direction::Up
$result->toArray();                  // normalized API payload

// A gap-filled daily series.
$trend = Metrics::query(Order::class)
    ->count()
    ->range('mtd')
    ->perDay()
    ->trend();

// A group-by breakdown with engine-computed percentages.
$partition = Metrics::query(Order::class)
    ->count()
    ->groupBy('status')
    ->top(5)              // fold the tail into "others"
    ->partition();

->range('qtd')                                    // named
->range('12mo')                                   // rolling
->between('2026-01-01', '2026-06-30')             // explicit period
->allTime()                                       // unbounded

Metrics::query(Order::class)
    ->average('total')
    ->range('ytd')
    ->per(Interval::Week)      // Minute | Hour | Day | Week | Month | Quarter | Year
    ->timezone('Asia/Kolkata') // minute-precision bucket shifting
    ->trend();

->compareWithPrevious()          // immediately preceding period
->compareWithPreviousWeek()      // same window, shifted back
->compareWithPreviousMonth()     //   (no month-overflow surprises)
->compareWithPreviousQuarter()
->compareWithPreviousYear()
->compareWith($customStrategy)   // your own ComparisonStrategy

$result = Metrics::query(Order::class)
    ->range('30d')
    ->dataset('revenue', fn ($d) => $d->sum('total'))
    ->dataset('refunds', fn ($d) => $d->sum('refund_total'))
    ->dataset('expenses', fn ($d) => $d->sum('amount')->from(Expense::class))
    ->formula('profit', '[revenue] - [refunds] - [expenses]')
    ->formula('margin', 'profit / revenue * 100')
    ->value();

$result->value('margin'); // 37.5

class OrdersRevenue extends Metric
{
    public function query(): MetricBuilder
    {
        return Metrics::query(Order::class)
            ->sum('total')->range('30d')->compareWithPrevious()->cache(300);
    }
}

// e.g. in a controller:
Route::get('/api/metrics/{key}', function (string $key, Request $request) {
    return Metrics::run($key, $request->only(['range', 'interval', 'timezone', 'compare']));
});

Metrics::register(SomeOtherPackage\Metrics\Signups::class);

'generator' => [
    'namespace' => 'App\\Metrics',   // the namespace generated classes declare
    'path' => app_path('Metrics'),  // where they're written
    'stub' => null,                 // an absolute path to fully override the stub
    'base_class' => Metric::class,  // the class generated metrics extend
],

// app/Metrics/Revenue.php — written by hand or by `make:metric` —
// is registered automatically. Just run it:
Metrics::run('revenue');

'discover' => false,

->cache(600)      // seconds; any Laravel TTL value works
->fresh()         // bypass for one execution

use Syriable\Metrics\Aggregates\CallbackAggregate;
use Syriable\Metrics\Ranges\CallbackRange;
use Syriable\Metrics\Comparisons\CallbackComparison;

// A new aggregation — no core changes:
Metrics::registerAggregate(new CallbackAggregate(
    'stddev', fn (string $inner) => "stddev({$inner})",
));

// A fiscal-year range:
Metrics::registerRange(new CallbackRange('fiscal_ytd', 'Fiscal YTD',
    fn (CarbonImmutable $now) => new Period($now->setMonth(4)->startOfMonth(), $now),
));

// A custom reference window:
Metrics::registerComparison(new CallbackComparison('vs_launch',
    fn (Period $current) => Period::between('2026-01-01', '2026-01-31'),
));

// A new database driver — one class:
Metrics::registerDialect(new FirebirdDialect);

// Your own payload shape / expression language:
Metrics::useSerializer(new JsonApiSerializer);
Metrics::useFormulaEvaluator(new SymfonyExpressionEvaluator);
bash
php artisan make:metric Revenue

INFO  Metric [app/Metrics/Revenue.php] created successfully.
bash
php artisan make:metric Sales/Revenue   # App\Metrics\Sales\Revenue
bash
php artisan vendor:publish --tag="laravel-metrics-stubs"