Speed Up Laravel 7: Eloquent Query Caching

Laravel Project
1 min readJul 24, 2020

--

When your laravel application is slow, caching can be of the best way to gain performance. Additionally, laravel provides 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 you application way faster. 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 a 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

Then, after installing the package you can simply apply the trait provided Rememberable to you Model.

<?php
namespace App;
use Watson\Rememberable\Rememberable;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use Rememberable;
}

Also, You can extract an abstract class which extends you 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
}

Read all the details of the post in https://laravelproject.com/speed-up-laravel-7-eloquent-query-caching/

--

--

Laravel Project

(laravelproject.com) Online resource for tutorial articles and open source projects for learning laravel framework.