Laravel Stats: Track Application Stats and Their Change Over Time

Packages

July 22nd, 2021

laravel-stats-featured.png

Laravel Stats is a package by Spatie to easily track application stats like orders, subscriptions, and users, and their change over time.

This package is simple to use and get started with—you extend the package's BaseStats class, and you are ready to use this package:

1use Spatie\Stats\BaseStats;
2 
3class SubscriptionStats extends BaseStats {}

Next, whenever you want to track a stat, you can increase or decrease the statistic:

1// execute whenever somebody subscribes
2SubscriptionStats::increase();
3 
4// execute whenever somebody cancels the subscription
5SubscriptionStats::decrease();
6 
7// Set the stat directly
8SubscriptionStats::set($count);

Once you've collected stats, you can query statistics with this package using the provided StatsQuery API:

1$stats = SubscriptionStats::query()
2 ->start(now()->subMonths(2))
3 ->end(now()->subSecond())
4 ->groupByWeek()
5 ->get();
6 
7/*
8Example results:
9 
10[
11 [
12 'start' => '2020-01-01',
13 'end' => '2020-01-08',
14 'value' => 102,
15 'increments' => 32,
16 'decrements' => 20,
17 'difference' => 12,
18 ],
19 [
20 'start' => '2020-01-08',
21 'end' => '2020-01-15',
22 'value' => 114,
23 'increments' => 63,
24 'decrements' => 30,
25 'difference' => 33,
26 ],
27]
28 
29*/

You can learn more about this package, get full installation instructions, and view the source code on GitHub. The package author also wrote a detailed post about this package.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.