Improving Laravel Loading Speed Using Redis Cache

Ivan Radunovic

Feb 20, 202412 min read
Improving Laravel Loading Speed Using Redis Cache

Redis is an in-memory data structure store, it's used as a database, cache, and message broker. Integrating Redis with Laravel can significantly improve your application's loading speed by caching database queries, reducing the load on the database, and speeding up response times.

In this tutorial you'll learn the best way to implement Redis into Laravel application. It should take you maximum of 5 minutes to complete described steps and cache first query.

What is a Cache?

Cache is a high-speed data storage layer that stores a subset of data, typically temporary in nature, so that future requests for that data can be served faster than accessing the data's primary storage location.

Data stored in a cache might include web pages, database queries, computational results, or files.

Caching mechanisms can be implemented in hardware or software, and are found at various levels in technology architectures, including within CPU architectures, web browsers, operating systems, and application frameworks.

What is Redis?

Redis is a type of cache which uses server memory to store data. By using server memory it can return results faster than reading from disk or a SQL database.

In order to use Redis Cache in Laravel application it first needs to be installed on the server or development environment.

Installing Redis on Ubuntu Server

To install Redis on an Ubuntu server, follow these steps, ensuring you have administrative rights (sudo) on the server:

  1. Update Ubuntu's Package Index: Begin by updating the package index on your Ubuntu server. Open a terminal and execute the following command:
sudo apt update
  1. Install Redis: After updating the package index, install Redis by running:
sudo apt install redis-server

This command downloads and installs the Redis server along with its dependencies.

  1. Configure Redis as a Service: By default, Redis installs as a systemd service and should start automatically. To ensure Redis is running, use:
sudo systemctl status redis-server

If Redis is not running, you can start it with:

sudo systemctl start redis-server
  1. Enable Redis to Start at Boot: To ensure Redis starts automatically at boot, enable the service:
sudo systemctl enable redis-server
  1. Configure Redis (Optional): To configure Redis to your needs, edit the Redis configuration file located at /etc/redis/redis.conf. You can open this file in a text editor with root permissions, for example:
sudo nano /etc/redis/redis.conf

After making your changes, restart Redis to apply them:

sudo systemctl restart redis-server
  1. Test Redis Installation: Finally, test that Redis is properly installed and running by connecting to the Redis server using the command-line client:
redis-cli

In the Redis command line, try a simple command to test functionality, like ping, which should return a response of PONG if Redis is operational.

This section outlines the basic steps to install Redis on an Ubuntu server, including starting the service and making it run at boot. Further configuration might be required based on specific use cases or security considerations.

If you're using Laravel Forge and choose an app server, Redis is pre-installed there.

Configuring Redis Cache in Laravel Application

In order to use Redis as cache Laravel requires predis/predis composer package.

composer require predis/predis

Redis Configuration File

Inside config/database.php you'll find redis array which defines all variables for a connection.


    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],

        'cache' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CACHE_DB', '1'),
        ],

    ],

Usually default Laravel env variables are good for Redis, but if you changed anything you can update it using respective env variables.

One thing that should be changed in env is:

REDIS_CLIENT=predis
CACHE_DRIVER=redis

You can also use Redis for queues and broadcasts:

BROADCAST_DRIVER=redis
QUEUE_CONNECTION=redis

Now Redis is connected to our Laravel application and we can write actual caching code.

Detecting slow queries in Laravel

The easiest option to detect slow queries in development is Laravel Debugbar.

Install it with:

composer require barryvdh/laravel-debugbar --dev

In Queries tab Debugbar will display all queries behing the current request and you'll be able to see time and memory they took.

First thing in optimization is to modify and improve Eloquent queries and only after you've done that move to caching.

How to cache in Laravel?

Queries that are common among different users but frequent should be cached. One such example is displaying a list of posts on the blog page. Since every user sees same list.

Other case could be related posts for a certain category.

UI elements that are loaded from the database, for example header menu, footer links, sidebar links etc. But you should cache only variables and pass them to blade.

Cache validity - Automatic invalidation

The best option is to set a number of seconds for which cached variable will be kept in cache, after that Laravel will refresh the variable.

Laravel posses Cache::remember() function for this:

Cache::remember('posts', 60 * 10, function () {
	return App\Models\Post::orderBy('id', 'desc')->take(10)->get();
});

Code above will store posts keys in the cache, which will be saved for 10 minutes. If variable is missing from the cache it'll run the query in the callback.

Neat and simple!

What not to cache?

You should not cache elements of the UI as is, in HTML. That's not efficient from the perspective of Redis.

In Redis you should store only pure values.

Also storing images or files in cache is not optimal solution. Instead for hosting files you should use S3 or some CDN.

Share
Author Photo
Ivan Radunovic is a Senior Developer with over 11 years of experience in web development. His expertise are Laravel SaaS solutions. So far he developed or took part in 300+ Laravel projects.

More Laravel tutorials

Automatically purge Cloudflare Cache on new Deployment

After new deployment and compiling it's important to clear Cloudflare cache, otherwise it'll serve old assets.

Feb 29, 2024 Ivan Radunovic

Cloudflare Turnstile Laravel - Protect your app from bots

Turnstile will protect forms on sites from abusive bots. It's a hassle free alternative for Google ReCaptcha.

Feb 27, 2024 Ivan Radunovic

Login into Laravel application with a Magic link

Magic link authentication is a popular choice for login pages. User can request a link and click on it and he'll be authenticated.

Feb 24, 2024 Ivan Radunovic

Send Laravel notifications to Telegram messenger

Keeping track of your Laravel application is super important, integrating Laravel with Telegram messenger will help you gain better real-time insights.

Feb 21, 2024 Ivan Radunovic

Laravel SSO authentication with Google One Tap logins

Single sign-on authentication became a standard so we teach you how to implement it in your app. On top of that we'll show you how to integrate Google One Tap authentication flow also.

Feb 13, 2024 Ivan Radunovic

Google ReCaptcha in Laravel - Protect Laravel forms from bots

Learn how to integrate Google ReCAPTCHA into Laravel application, applies for types v2 and v3. All about I'm not a robot checkbox, invisible captcha and score based captcha.

Feb 12, 2024 Ivan Radunovic

Advanced querying with whereHas Method in Laravel Eloquent

The whereHas method in Laravel allows to filter models based on conditions of their related models, simplifying complex queries involving relationships.

Feb 05, 2024 Ivan Radunovic

Soft Delete in Laravel

With Laravel soft delete trait you can mark certain Eloquent model as deleted, and they will be removed from general queries. But you can query them with special methods.

Feb 04, 2024 Ivan Radunovic