PHPackages                             mattkingshott/statistics - 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. [Database &amp; ORM](/categories/database)
4. /
5. mattkingshott/statistics

Abandoned → [caneara/statistics](/?search=caneara%2Fstatistics)ArchivedLibrary[Database &amp; ORM](/categories/database)

mattkingshott/statistics
========================

A package to maintain statistics on database records

v2.0.0(4y ago)4691MITPHPPHP ^8.0

Since Feb 7Pushed 3y agoCompare

[ Source](https://github.com/caneara/statistics)[ Packagist](https://packagist.org/packages/mattkingshott/statistics)[ Docs](https://github.com/mattkingshott/statistics)[ RSS](/packages/mattkingshott-statistics/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (4)Dependencies (3)Versions (5)Used By (0)

Statistics
==========

[](#statistics)

This package enables a Laravel application to maintain aggregated statistics for database tables. It serves as a companion package to (and relies upon) [triggers](https://github.com/caneara/triggers).

Who is this for?
----------------

[](#who-is-this-for)

If you're running queries that are slow because they need to perform aggregations (`COUNT`, `SUM`, `MIN`, `MAX` or `AVG`) across many records, then you might get some value from this package. A common scenario where this takes place, is on a dashboard that displays lots of statistics e.g.

```
SELECT
    (SELECT COUNT(*) FROM `articles`) AS 'articles',
    (SELECT COUNT(*) FROM `projects`) AS 'projects',
    (SELECT COUNT(*) FROM `tasks`) AS 'tasks'
```

By contrast, you can configure the package to automatically maintain statistics in the background. So, instead of a slow query (like the above example), you can instead do this:

```
SELECT
    `table`, `values`
FROM
    `statistics`
WHERE
    `table`
IN
    ('articles', 'projects', 'tasks')
```

Or, better still, use the Eloquent model to query the data:

```
use Statistics\Models\Statistic;

$stats = Statistic::query()
    ->whereIn('table', ['articles', 'projects', 'tasks'])
    ->get(['table', 'values']);
```

TableValuesArticles`{ "count" : 6 }`Projects`{ "count" : 3 }`Tasks`{ "count" : 2 }`Installation
------------

[](#installation)

Pull in the package using Composer:

```
composer require caneara/statistics
```

Configuration
-------------

[](#configuration)

The package includes a configuration file that allows you to change the name of the database table that contains the aggregated values (the default is 'statistics'). If you want to change it, publish the configuration file using Artisan:

```
php artisan vendor:publish
```

Usage
-----

[](#usage)

The package will automatically register and migrate a `statistics` table to your database. This table then serves as a repository for aggregated values. The values are maintained using database triggers, which will automatically fire after a record is inserted, updated or deleted.

> Before proceeding further, it is important to remember that database triggers (which the package relies on) can only be added to a table after it has been created. In other words, don't try to create statistics for a table before it has been created by `Schema::create` (this will become clearer in the examples below).

To begin, add the `InteractsWithStatistics` trait to any `Model` class that you want to maintain statistics for e.g.

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Statistics\InteractsWithStatistics;

class Article extends Model
{
    use InteractsWithStatistics;
}
```

Next, call the static `track` method on the `Model`.

```
Article::track();
```

Next, call one or more of the available aggregation methods:

```
Article::track()
    ->count()           // Count all records
    ->sum('likes')      // Get the sum of all records using the 'likes' column
    ->average('likes')  // Get the average value from the 'likes' column
    ->minimum('likes')  // Get the smallest value in the 'likes' column
    ->maximum('likes'); // Get the largest value in the 'likes' column
```

You can call an aggregation method more than once if you need to maintain statistics on multiple columns. Simply supply a custom name to differentiate them:

```
Article::track()
    ->count()
    ->sum('likes', 'sum_likes')
    ->sum('views', 'sum_views');
```

Finally, call the `create` method to install the triggers.

```
Article::track()
    ->count()
    ->create();
```

#### Example

[](#example)

Here's a simple example within a database migration:

```
class CreateArticlesTable extends Migration
{
    public function up() : void
    {
        Schema::create('articles', function(Blueprint $table) {
            $table->unsignedTinyInteger('id');
            $table->string('title');
        });

        Article::track()
            ->count()
            ->create();
    }
}
```

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

[](#contributing)

Thank you for considering a contribution to the package. You are welcome to submit a PR containing improvements, however if they are substantial in nature, please also be sure to include a test or tests.

License
-------

[](#license)

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

###  Health Score

28

—

LowBetter than 52% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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 ~0 days

Total

4

Last Release

1605d ago

Major Versions

v1.0.2 → v2.0.02022-02-08

### Community

Maintainers

![](https://www.gravatar.com/avatar/22bc3f376c7511f4fc85e2c240cf52c075c491426795c71409c0a4b551a8bf85?d=identicon)[mattkingshott](/maintainers/mattkingshott)

---

Top Contributors

[![mattkingshott](https://avatars.githubusercontent.com/u/51963402?v=4)](https://github.com/mattkingshott "mattkingshott (19 commits)")

---

Tags

phplaraveldatabasestatistics

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mattkingshott-statistics/health.svg)

```
[![Health](https://phpackages.com/badges/mattkingshott-statistics/health.svg)](https://phpackages.com/packages/mattkingshott-statistics)
```

###  Alternatives

[renoki-co/l1

Laravel integration for Cloudflare Workers services.

16321.9k](/packages/renoki-co-l1)[wayofdev/laravel-cycle-orm-adapter

🔥 A Laravel adapter for CycleORM, providing seamless integration of the Cycle DataMapper ORM for advanced database handling and object mapping in PHP applications.

3535.8k3](/packages/wayofdev-laravel-cycle-orm-adapter)[tomatophp/filament-locations

Database Seeds for Countries / Cities / Areas / Languages / Currancy with ready to use resources for FilamentPHP

2323.2k6](/packages/tomatophp-filament-locations)

PHPackages © 2026

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