PHPackages                             kanazaca/counter-cache - 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. kanazaca/counter-cache

ActiveLibrary[Database &amp; ORM](/categories/database)

kanazaca/counter-cache
======================

Package for Laravel to implement counter cache

1.0.1(10y ago)1563.7k↑34.4%5[1 issues](https://github.com/kanazaca/counter-cache/issues)MITPHP

Since Dec 17Pushed 8y ago2 watchersCompare

[ Source](https://github.com/kanazaca/counter-cache)[ Packagist](https://packagist.org/packages/kanazaca/counter-cache)[ RSS](/packages/kanazaca-counter-cache/feed)WikiDiscussions master Synced today

READMEChangelog (2)DependenciesVersions (3)Used By (0)

Counter Cache for Laravel - Updated 11/10/2016
==============================================

[](#counter-cache-for-laravel---updated-11102016)

Counter Cache for Laravel

Why ?
-----

[](#why-)

Imagine if you have to show 50 products in a list and have to show a counter for how many comments that product have, too much queries, right ? This package will allow you to super reduce the number of queries made.

Feature Overview
----------------

[](#feature-overview)

- Increment counter automatically when creating a new record.
- Decrement counter automatically when deleting a record.
- Update counter automatically when updating a record
- ...

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

[](#installation)

Add this to your composer.json file, in the require object:

```
"kanazaca/counter-cache": "1.0.*"
```

After that, run composer install to install the package. Add the service provider to `config/app.php`, within the `providers` array.

```
'providers' => array(
	// ...
	kanazaca\CounterCache\CounterCacheServiceProvider::class,
)
```

Basic Usage
-----------

[](#basic-usage)

I will use the example products/comments, one product have many comments

### Migration

[](#migration)

You need to create a field in the table that you want access the counter, like the example below:

```
Schema::create('products', function (Blueprint $table) {
      $table->increments('id');
      $table->string('name');
      $table->string('ref');
      $table->integer('comments_count')->default(0); // This is the counter that you have to add
      $table->timestamps();
  });
```

After this run `php artisan migrate`

### Model

[](#model)

Comments model, you have to use the trait, define the $counterCacheOptions and make the relation with the product :

```
namespace App;

use Illuminate\Database\Eloquent\Model;
use kanazaca\CounterCache\CounterCache;

class Comments extends Model
{
    use CounterCache;

    // you can have more than one counter
    public $counterCacheOptions = [
        'Product' => ['field' => 'comments_count', 'foreignKey' => 'product_id']
    ];

    public function Product()
    {
        return $this->belongsTo('App\Product');
    }
}
```

Filters
-------

[](#filters)

If you want to do some filtering before the counter cache magic happens, you have to add the key `filter` to `$counterCacheOptions` with the name of your method that will provide the filter, as string, like below:

```
public $counterCacheOptions = [
    'Product' => [
        'field' => 'comments_count',
        'foreignKey' => 'product_id',
        'filter' => 'CommentValidatedFilter'
    ]
]; // you can have more than one counter

// this code will be executed before the counting (save and update method)
public function CommentValidatedFilter()
{
    if ($this->validated) {
        return true;
    }

    return false;
}
```

Credits
-------

[](#credits)

Hugo Neto

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 90% 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 ~159 days

Total

2

Last Release

3692d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/526428777636a364e981699dd701f0a4207f9a58100e31d12c6cbb75df158e9a?d=identicon)[kanazaca](/maintainers/kanazaca)

---

Top Contributors

[![kanazaca](https://avatars.githubusercontent.com/u/8916773?v=4)](https://github.com/kanazaca "kanazaca (9 commits)")[![simaolemos](https://avatars.githubusercontent.com/u/7593214?v=4)](https://github.com/simaolemos "simaolemos (1 commits)")

### Embed Badge

![Health badge](/badges/kanazaca-counter-cache/health.svg)

```
[![Health](https://phpackages.com/badges/kanazaca-counter-cache/health.svg)](https://phpackages.com/packages/kanazaca-counter-cache)
```

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k117.2M118](/packages/jdorn-sql-formatter)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M87](/packages/propel-propel1)[pgvector/pgvector

pgvector support for PHP

198741.5k12](/packages/pgvector-pgvector)[jfelder/oracledb

Oracle DB driver for Laravel

11518.4k](/packages/jfelder-oracledb)

PHPackages © 2026

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