Speed Up Laravel 7: Eloquent Query Caching

When your laravel application is slow, caching can be of the best way to gain performance. Additionally, laravel provides a bunch of built-in caching methods to handle cache in different ways like Redis, Memcached, and file cache.

Caching can minimize your page load time drastically and make your application way faster. However, Laravel’s performance by default can be slow if you are executing a lot of eloquent queries at page load. After all, caching most of these heavy queries can lift some load from your server and make your application load faster.

In this tutorial, we will use a query caching package, thus making it super easy to cache your query results for an adjustable amount of time.

Installation of the Query Caching Package

First, we will use Composer to install the package in our laravel project.

composer require watson/rememberable
<?php
namespace App;

use Watson\Rememberable\Rememberable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use Rememberable;
}

In addition, You can extract an abstract class that extends your existing Eloquent Model but also has Rememberable trait included.

<?php
namespace App;

use Watson\Rememberable\Rememberable;
use Illuminate\Database\Eloquent\Model as Eloquent;

abstract class Post extends Eloquent
{
    use Rememberable;
}

Now, you simply extend the newly created Model class and every other Eloquent model will automatically inherit the caching functionality.

<?php
namespace App;

class Post extends Model
{
    // now caching is available
}

Basic Usage of Query Caching

The caching query is simple. Now, you just have to add remember() to your existing eloquent queries and pass seconds as a parameter for expiry time.

// Remember posts for an hour.
$posts = Post::remember(60 * 60)->get();

To clear all cache, simply use this function.

Post::flushCache();

Add cacheTags()and pass the tag name if you want to reference certain queries to be flushed but not all. Note! not supported by all cache drivers.

// Remember posts for an hour and tag it with 'post_queries'
Post::remember(60 * 60)->cacheTags('post_queries')->get();

// And later you can flush cache with only certain tags
Post::flushCache('post_queries');

You can also skip caching for specific models using dontRemember function.

Post::latest()->dontRemember()->get();

Asmit Nepali, a Full Stack Developer, holds a Software Engineering degree from Gandaki College of Engineering and Science. Proficient in PHP Laravel, Vue.js, MySQL, Tailwind, Figma, and Git, he possesses a robust technical skill set.

Leave a Comment