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. Although, Laravel’s performance by default can be slow if you are executing a lot of eloquent queries at page load. Afterall, caching most of these heavy queries can lift some load from your server and makes your application load faster.

In this tutorial, we will use query caching package, thus making 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 newely 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 model using dontRemember function.

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

Finally, your application is ready to cache every queries.

Total
0
Shares
Leave a Reply

Your email address will not be published.

Total
0
Share