Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

A lightweight Laravel package to track changes over time

Original – by Alex Vanderbist and Freek Van der Herten – 3 minute read

I'm proud to announce that our team has released a new package called spatie/laravel-stats. This package is a lightweight solution for summarizing changes in your database over time.

Tracking changes

Here's a quick example where we will track the number of subscriptions and cancellations over time.

First, you should create a stats class.

use Spatie\Stats\BaseStats;

class SubscriptionStats extends BaseStats {}

Next, you can call increase when somebody subscribes and decrease when somebody cancels their plan.

SubscriptionStats::increase(); // execute whenever somebody subscribes
SubscriptionStats::decrease() // execute whenever somebody cancels the subscription;

With this in place, you can query the stats. Here's how you can get the subscription stats for the past two months, grouped by week.

use Spatie\Stats\StatsQuery;

$stats = StatsQuery::for(SubscriptionStats::class)
    ->start(now()->subMonths(2))
    ->end(now()->subSecond())
    ->groupByWeek()
    ->get();

This will return an array like this one:

[
    [
        'start' => '2020-01-01',
        'end' => '2020-01-08',
        'value' => 102,
        'increments' => 32,
        'decrements' => 20,
        'difference' => 12,
    ],
    [
        'start' => '2020-01-08',
        'end' => '2020-01-15',
        'value' => 114,
        'increments' => 63,
        'decrements' => 30,
        'difference' => 33,
    ],
]

Instead of manually increasing and decreasing the stat, you can directly set it. This is useful when your particular stat does not get calculated by your own app but lives elsewhere. Using the subscription example, let's imagine that subscriptions live elsewhere and that there's an API call to get the count.

$count = AnAPi::getSubscriptionCount(); 

SubscriptionStats::set($count);

By default, that increase, decrease and sets methods assume that the event that caused your stats to change happened right now. Optionally, you can pass a date time as a second parameter to these methods. Your stat change will be recorded as if it happened at that moment.

SubscriptionStats::increase(1, $subscription->created_at); 

How it works on under the hood

The implementation of this package is simple. The basic principles of event sourcing are being used: we don't store a result, but only the changes.

The package stores all "events" in the stats_event table

screenshot

Inside the StatsQuery class, you'll find the heart of the package. In its get function, you can see that all events for a given period are retrieved, summarized and mapped to DataPoint classes.

In closing

We are going to use laravel-stats in Flare, our exception tracker for Laravel/PHP/JavaScript projects, to keep tracker of changes in subscribers and other key metrics. We hope that the package can be helpful in your projects as well.

As mentioned above, the package uses a lightweight event sourcy approach. If you want to know more about event sourcing, check out our upcoming premium course on event sourcing in Laravel.

I'd like to thank my colleague Alex, who did the bulk of the work creating spatie/laravel-stats.

Do also take a look at this list of packages our team has created previously. I'm sure there's something there for your next project.

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments

What are your thoughts on "A lightweight Laravel package to track changes over time"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.