Laravel News: Laravel Model Caching
On the Laravel News site they’ve posted a tutorial showing you how to use the caching functionality for models based on the framework’s Eloquent ORM layer. This caching makes for fewer queries to the database and can improve the overall performance of the application.
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.
They start with an example of it in action, getting the count of comments on a news article based on a relationship. It then shows the use of the
touch method to change the model’s
updated_at timestamp to the current time allowing you to more correctly detect when changes occur. It also includes a more automatic way of performing the same operation using the
$touches class property on the model and the
cacheKey method to create a unique key name for use in the caching system to reference the model contents.