Cache Eloquent queries in Laravel 6

Alex Renoki
Nov 23 · 2 min read

When it comes to speeding up your application, caching can be the best thing to achieve. Laravel comes up with cache drivers pre-installed so you can enjoy the experience out-of-the-box. Redis, Memcached or just using local files, Laravel comes packed with this.

This time, we will talk about caching Eloquent queries directly from the models, thus making the database caching a breeze!

The package can be found on GitHub, where the documentation will approach all of the main points of the app. However, during this article, you’ll learn just the basics of caching and clearing cache so you can get started before you will dig deeper.


The package can be installed through Composer:

Your models will need the trait:

Enable the caching behavior by default

By default, the package does not enable query caching. To achieve this, add the variable in your model:

Whenever a query will be triggered, the cache will intervene and in case the cache is empty for that query, it will store it and next time will retrieve it from the caching database; in case it exists, it will retrieve it and serve it, without hitting the database.

If you simply want to avoid hitting the cache, you can use the before hitting the final method.

Enable the caching behavior query-by-query

The alternative is to enable cache query-by-query if caching by default doesn’t sound like a good option to you.

First of all, remove the variable from your model.

On each query, you can call to specify that you want to cache that query.

Organize better with tags

Some cache storages, like Redis or Memcached, come up with the support of tagging your keys. This is useful because we can tag our queries in-cache and invalidate the needed cache whenever we want to.

As a simple example, this can be useful if we want to invalidate the articles list cache when one article gets updated.

The method invalidates only the caches that were tagged with . If some other queries would have been tagged with tags other than , they would be kept in the cache.

Digging deeper

For more about this package, check out the project’s page on GitHub.

The Startup

Medium's largest active publication, followed by +538K people. Follow to join our community.

Alex Renoki

Written by

🇷🇴 Certified Laravel Developer. Full-stacking with Vue.js and AWS.

The Startup

Medium's largest active publication, followed by +538K people. Follow to join our community.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade