Implementing counter caching on your models - ml-archive/nodes-php-counter-cache GitHub Wiki

Implementing counter-caching on your models is quite simple.

So let's imagine we have a User model and a Post model. Everytime we create a new post, we want to update the field posts_count on our User model. This way, we can easy and quick show how many posts each user has created.

First you need implement the CounterCacheable interface on your model. You need to implement the interface on the model where you wish to execute the Counter Cache from - which in our case means - we need to implement it on our Post model.

use Nodes\CounterCache\CounterCacheable

class Post implements CounterCacheable
{

}

The interface requires you to implement the counterCaches method. The method should always return an array.

use Nodes\CounterCache\CounterCacheable

class Post implements CounterCacheable
{
    /**
     * Retrieve array of counter caches.
     *
     * @return array
     */
    public function counterCaches()
    {
        return [];
    }
}

The counterCaches method is where you define the counter caches you wish to implement on your model. To learn how to define your counter-caches, jump to the next page on the Wiki.

Defining your counter caches →