Laravel Model Caching

Tutorials

January 11th, 2018

laravel-model-caching.png

You’ve probably cached some model data in the controller before, but I am going to show you a Laravel model caching technique that’s a little more granular using Active Record models. This is a technique I originally learned about on RailsCasts.

Using a unique cache key on the model, you can cache properties and associations on your models that are automatically updated (and the cache invalidated) when the model (or associated model) is updated. A side benefit is that accessing the cached data is more portable than caching data in the controller, because it’s on the model instead of within a single controller method.

Here’s the gist of the technique:

Let’s say you have an Article model that has many Comment models. Given the following Laravel blade template, you might retrieve the comment count like so on your /article/:id route:

1<h3>{{ str_plural('Comment', $article->comments->count()) }}</h3>

You could cache the comment count in the controller, but the controller can get pretty ugly when you have multiple one-off queries and data you need to cache. Using the controller, accessing the cached data isn’t very portable either.

We can build a template that will only hit the database when the article is updated, and any code that has access to the model can grab the cached value:

1<h3>{{ str_plural('Comment', $article->cached_comments_count) }}</h3>

Using a model accessor, we will cache the comment count based on the last time the article was updated.

So how do we update the article’s updated_at column when a new comment is added or removed?

Enter the touch method.

Touching Models

Using the model’s touch() method, we can update an article’s updated_at column:

1$ php artisan tinker
2 
3>>> $article = \App\Article::first();
4=> App\Article {#746
5 id: 1,
6 title: "Hello World",
7 body: "The Body",
8 created_at: "2018-01-11 05:16:51",
9 updated_at: "2018-01-11 05:51:07",
10 }
11>>> $article->updated_at->timestamp
12=> 1515649867
13>>> $article->touch();
14=> true
15>>> $article->updated_at->timestamp
16=> 1515650910

We can use the updated timestamp to invalidate a cache, but how can we touch the article’s updated_at field when we add or remove a comment?

It just so happens that Eloquent models have a property called $touches. Here’s what our comment model might look like:

1namespace App;
2 
3use App\Article;
4use Illuminate\Database\Eloquent\Model;
5 
6class Comment extends Model
7{
8 protected $guarded = [];
9 
10 protected $touches = ['article'];
11 
12 public function article()
13 {
14 return $this->belongsTo(Article::class);
15 }
16}

The $touches property is an array containing the association that will get “touched” when a comment is created, saved, or removed.

The Cached Attribute

Let’s go back to the $article->cached_comments_count accessor. The implementation might look like this on the App\Article model:

1public function getCachedCommentsCountAttribute()
2{
3 return Cache::remember($this->cacheKey() . ':comments_count', 15, function () {
4 return $this->comments->count();
5 });
6}

We are caching the model for fifteen minutes using a unique cacheKey() method and simply returning the comment count inside the closure.

Note that we could also use the Cache::rememberForever() method and rely on our caching mechanism’s garbage collection to remove stale keys. I’ve set a timer so that the cache will be hit most of the time, with a fresh cache every fifteen minutes.

The cacheKey() method needs to make the model unique, and invalidate the cache when the model is updated. Here’s my cacheKey implementation:

1public function cacheKey()
2{
3 return sprintf(
4 "%s/%s-%s",
5 $this->getTable(),
6 $this->getKey(),
7 $this->updated_at->timestamp
8 );
9}

The example output for the model’s cacheKey() method might return the following string representation:

1articles/1-1515650910

The key is the name of the table, the model id, and the current updated_at timestamp. Once we touch the model, the timestamp will be updated, and our model cache will be invalidated appropriately.

Here’s the Article model if full:

1namespace App;
2 
3use App\Comment;
4use Illuminate\Support\Facades\Cache;
5use Illuminate\Database\Eloquent\Model;
6 
7class Article extends Model
8{
9 public function cacheKey()
10 {
11 return sprintf(
12 "%s/%s-%s",
13 $this->getTable(),
14 $this->getKey(),
15 $this->updated_at->timestamp
16 );
17 }
18 
19 public function comments()
20 {
21 return $this->hasMany(Comment::class);
22 }
23 
24 public function getCachedCommentsCountAttribute()
25 {
26 return Cache::remember($this->cacheKey() . ':comments_count', 15, function () {
27 return $this->comments->count();
28 });
29 }
30}

And the associated Comment model:

1namespace App;
2 
3use App\Article;
4use Illuminate\Database\Eloquent\Model;
5 
6class Comment extends Model
7{
8 protected $guarded = [];
9 
10 protected $touches = ['article'];
11 
12 public function article()
13 {
14 return $this->belongsTo(Article::class);
15 }
16}

What’s Next?

I’ve shown you how to cache a simple comment count, but what about caching all the comments?

1public function getCachedCommentsAttribute()
2{
3 return Cache::remember($this->cacheKey() . ':comments', 15, function () {
4 return $this->comments;
5 });
6}

You might also choose to convert the comments to an array instead of serializing the models to only allow simple array access to the data on the frontend:

1public function getCachedCommentsAttribute()
2{
3 return Cache::remember($this->cacheKey() . ':comments', 15, function () {
4 return $this->comments->toArray();
5 });
6}

Lastly, I defined the cacheKey() method on the Article model, but you would want to define this method via a trait called something like ProvidesModelCacheKey that you can use on multiple models or define the method on a base model that all our models extend. You might even want to use a contract (interface) for models that implement a cacheKey() method.

I hope you’ve found this simple technique useful!

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.