Laravel Model Caching

Published on by

Laravel Model Caching image

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:

<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:

<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:

$ php artisan tinker
 
>>> $article = \App\Article::first();
=> App\Article {#746
id: 1,
title: "Hello World",
body: "The Body",
created_at: "2018-01-11 05:16:51",
updated_at: "2018-01-11 05:51:07",
}
>>> $article->updated_at->timestamp
=> 1515649867
>>> $article->touch();
=> true
>>> $article->updated_at->timestamp
=> 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:

namespace App;
 
use App\Article;
use Illuminate\Database\Eloquent\Model;
 
class Comment extends Model
{
protected $guarded = [];
 
protected $touches = ['article'];
 
public function article()
{
return $this->belongsTo(Article::class);
}
}

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:

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

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:

public function cacheKey()
{
return sprintf(
"%s/%s-%s",
$this->getTable(),
$this->getKey(),
$this->updated_at->timestamp
);
}

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

articles/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:

namespace App;
 
use App\Comment;
use Illuminate\Support\Facades\Cache;
use Illuminate\Database\Eloquent\Model;
 
class Article extends Model
{
public function cacheKey()
{
return sprintf(
"%s/%s-%s",
$this->getTable(),
$this->getKey(),
$this->updated_at->timestamp
);
}
 
public function comments()
{
return $this->hasMany(Comment::class);
}
 
public function getCachedCommentsCountAttribute()
{
return Cache::remember($this->cacheKey() . ':comments_count', 15, function () {
return $this->comments->count();
});
}
}

And the associated Comment model:

namespace App;
 
use App\Article;
use Illuminate\Database\Eloquent\Model;
 
class Comment extends Model
{
protected $guarded = [];
 
protected $touches = ['article'];
 
public function article()
{
return $this->belongsTo(Article::class);
}
}

What’s Next?

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

public function getCachedCommentsAttribute()
{
return Cache::remember($this->cacheKey() . ':comments', 15, function () {
return $this->comments;
});
}

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:

public function getCachedCommentsAttribute()
{
return Cache::remember($this->cacheKey() . ':comments', 15, function () {
return $this->comments->toArray();
});
}

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!

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Version 4 of Tinkerwell is available now. Get the most popular PHP scratchpad with all its new features and simplify your development workflow today.

Visit Tinkerwell
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with Vue and Livewire stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4 image

Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4

Read article
Neovim Plugin to for Navigating Laravel and Livewire Components image

Neovim Plugin to for Navigating Laravel and Livewire Components

Read article
Laravel Herd v1.7 is out with updates to the dump UI image

Laravel Herd v1.7 is out with updates to the dump UI

Read article
Share Error Package for Laravel's New Exception Page image

Share Error Package for Laravel's New Exception Page

Read article
Sentry and Laravel announce a new partnership image

Sentry and Laravel announce a new partnership

Read article
"Fast Projects" by Larafast: Real life, ready to use Laravel based Boilerplates image

"Fast Projects" by Larafast: Real life, ready to use Laravel based Boilerplates

Read article