PHPackages                             spatie/laravel-stats - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. spatie/laravel-stats

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

spatie/laravel-stats
====================

Track application stat changes over time

2.3.1(1y ago)449259.2k—9%344MITPHPPHP ^8.2CI passing

Since Mar 29Pushed 8mo ago10 watchersCompare

[ Source](https://github.com/spatie/laravel-stats)[ Packagist](https://packagist.org/packages/spatie/laravel-stats)[ Docs](https://github.com/spatie/laravel-stats)[ GitHub Sponsors](https://github.com/sponsors/spatie)[ Fund](https://spatie.be/open-source/support-us)[ RSS](/packages/spatie-laravel-stats/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (15)Used By (4)

Track application stat changes over time
========================================

[](#track-application-stat-changes-over-time)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c7b796b69fbdbd65af8f036036e28c3160ae3a74a3f2256162ff21679d68b739/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d73746174732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-stats)[![Tests](https://github.com/spatie/laravel-stats/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/laravel-stats/actions/workflows/run-tests.yml)[![Total Downloads](https://camo.githubusercontent.com/3387c3c418097ca716308fb4df07d6ddc768ca52eca999c2035c4f2721811178/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d73746174732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-stats)

This package is a lightweight solution to summarize changes in your database over time. Here's a quick example where we are going to 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` on it 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 = SubscriptionStats::query()
    ->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,
    ],
]
```

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/eec8acc6cd7edcee3f91bc238f1a4e9188ff97a1c56b0bccc2a907a401220a85/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d73746174732e6a70673f743d32)](https://spatie.be/github-ad-click/laravel-stats)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require spatie/laravel-stats
```

You must publish and run the migrations with:

```
php artisan vendor:publish --provider="Spatie\Stats\StatsServiceProvider" --tag="stats-migrations"
php artisan migrate
```

Usage
-----

[](#usage)

### Step 1: create a stats class

[](#step-1-create-a-stats-class)

First, you should create a stats class. This class is responsible for configuration how a particular statistic is stored. By default, it needs no configuration at all.

```
use Spatie\Stats\BaseStats;

class SubscriptionStats extends BaseStats {}
```

By default, the name of the class will be used to store the statistics in the database. To customize the used key, use `getName`

```
use Spatie\Stats\BaseStats;

class SubscriptionStats extends BaseStats
{
    public function getName() : string{
        return 'my-custom-name'; // stats will be stored with using name `my-custom-name`
    }
}
```

Step 2: call increase and decrease or set a fixed value
-------------------------------------------------------

[](#step-2-call-increase-and-decrease-or-set-a-fixed-value)

Next, you can call `increase`, `decrease` when the stat should change. In this particular case, you should call `increase` on it when somebody subscribes, and `decrease` when somebody cancels their plan.

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

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 image 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 `set` 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 on that moment.

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

### Step 3: query the stats

[](#step-3-query-the-stats)

With this in place, you can query the stats. You can fetch stats for a certain period and group them by minute, hour, day, week, month, or year.

Here's how you can get the subscription stats for the past two months, grouped by week.

```
$stats = SubscriptionStats::query()
    ->start(now()->subMonths(2))
    ->end(now()->subSecond())
    ->groupByWeek()
    ->get();
```

This will return an array containing arrayable `Spatie\Stats\DataPoint` objects. These objects can be cast to arrays like this:

```
// output of $stats->toArray():
[
    [
        '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,
    ],
]
```

Extended Use-Cases
------------------

[](#extended-use-cases)

### Read and Write from a custom Model

[](#read-and-write-from-a-custom-model)

- Create a new table with `type (string)`, `value (bigInt)`, `created_at`, `updated_at` fields
- Create a model and add `HasStats`-trait

```
StatsWriter::for(MyCustomModel::class)->set(123)
StatsWriter::for(MyCustomModel::class, ['custom_column' => '123'])->increase(1)
StatsWriter::for(MyCustomModel::class, ['another_column' => '234'])->decrease(1, now()->subDay())

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

// OR

$stats = StatsQuery::for(MyCustomModel::class, ['additional_column' => '123'])
    ->start(now()->subMonths(2))
    ->end(now()->subSecond())
    ->groupByWeek()
    ->get();
```

### Read and Write from a HasMany-Relationship

[](#read-and-write-from-a-hasmany-relationship)

```
$tenant = Tenant::find(1)

StatsWriter::for($tenant->orderStats(), ['payment_type_column' => 'recurring'])->increment(1)

$stats = StatsQuery::for($tenant->orderStats(), , ['payment_type_column' => 'recurring'])
    ->start(now()->subMonths(2))
    ->end(now()->subSecond())
    ->groupByWeek()
    ->get();
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Alex Vanderbist](https://github.com/AlexVanderbist)
- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

56

—

FairBetter than 98% of packages

Maintenance53

Moderate activity, may be stable

Popularity55

Moderate usage in the ecosystem

Community33

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~110 days

Recently: every ~204 days

Total

14

Last Release

437d ago

Major Versions

0.0.1 → 1.0.02021-04-14

1.x-dev → 2.0.02022-03-04

PHP version history (2 changes)0.0.1PHP ^8.0

2.3.1PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (81 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (39 commits)")[![christoph-kluge](https://avatars.githubusercontent.com/u/1446269?v=4)](https://github.com/christoph-kluge "christoph-kluge (18 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (6 commits)")[![rubenvanassche](https://avatars.githubusercontent.com/u/619804?v=4)](https://github.com/rubenvanassche "rubenvanassche (4 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (4 commits)")[![finndev](https://avatars.githubusercontent.com/u/4342644?v=4)](https://github.com/finndev "finndev (3 commits)")[![bumbummen99](https://avatars.githubusercontent.com/u/4533331?v=4)](https://github.com/bumbummen99 "bumbummen99 (2 commits)")[![gauravmak](https://avatars.githubusercontent.com/u/11887260?v=4)](https://github.com/gauravmak "gauravmak (2 commits)")[![digitalkreativ](https://avatars.githubusercontent.com/u/3342987?v=4)](https://github.com/digitalkreativ "digitalkreativ (2 commits)")[![noamanahmed](https://avatars.githubusercontent.com/u/1734483?v=4)](https://github.com/noamanahmed "noamanahmed (2 commits)")[![skollro](https://avatars.githubusercontent.com/u/8849605?v=4)](https://github.com/skollro "skollro (1 commits)")[![abishekrsrikaanth](https://avatars.githubusercontent.com/u/1639302?v=4)](https://github.com/abishekrsrikaanth "abishekrsrikaanth (1 commits)")[![DexterHarrison](https://avatars.githubusercontent.com/u/8557148?v=4)](https://github.com/DexterHarrison "DexterHarrison (1 commits)")[![fsamapoor](https://avatars.githubusercontent.com/u/4992968?v=4)](https://github.com/fsamapoor "fsamapoor (1 commits)")[![ManojKiranA](https://avatars.githubusercontent.com/u/30294553?v=4)](https://github.com/ManojKiranA "ManojKiranA (1 commits)")[![SachinGanesh](https://avatars.githubusercontent.com/u/11994640?v=4)](https://github.com/SachinGanesh "SachinGanesh (1 commits)")[![abenerd](https://avatars.githubusercontent.com/u/7523903?v=4)](https://github.com/abenerd "abenerd (1 commits)")

---

Tags

spatielaravel-stats

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/spatie-laravel-stats/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-laravel-stats/health.svg)](https://phpackages.com/packages/spatie-laravel-stats)
```

###  Alternatives

[spatie/laravel-data

Create unified resources and data transfer objects

1.8k28.9M627](/packages/spatie-laravel-data)[spatie/laravel-livewire-wizard

Build wizards using Livewire

4061.0M4](/packages/spatie-laravel-livewire-wizard)[spatie/laravel-schedule-monitor

Monitor scheduled tasks in a Laravel app

9815.7M9](/packages/spatie-laravel-schedule-monitor)[spatie/laravel-feed

Generate rss feeds

9743.6M28](/packages/spatie-laravel-feed)[spatie/laravel-support-bubble

A non-intrusive support chat bubble that can be displayed on any page

391173.6k](/packages/spatie-laravel-support-bubble)[spatie/laravel-typescript-transformer

Transform your PHP structures to TypeScript types

3736.0M45](/packages/spatie-laravel-typescript-transformer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
