Model Cache Collections


Introduction

You might often find yourself wanting to cache data and invalidate it when an entry or stream is updated. Model cache collections let you do just that! This article will show you how it works and how to do it yourself.

Basic Usage

To get started first inject your repository into the class you will be working in. We'll assume a controller in this article. Then call the cache method on the repository just as you would with the cache manager in Laravel. The cache method expects key, lifetime, and value parameters.

public function example(PostRepositoryInterface $posts)
{
    return $posts->cache('example_key', 300, function() {
        return $this->view->make('module::my/complicated/view');
    });
}

Direct Model Use

The above example will cache the content of the closure for a maximum of 300 seconds and will invalidate should any entry in the posts stream be modified.

You can also call the cache method directly on the model:

public function example()
{
    return (new PostModel())->cache('example_key', 300, function() {
        return $this->view->make('module::my/complicated/view');
    });
}

Flushing Cache Manually

Though cache is invalidated automatically when any entry in the associated stream is updated, created, deleted, or mass updated you can also forcefully flush cache by calling flushCache() on either the model or repository.


No Comments


Leave a Comment