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:
- 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
- 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.
- 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
- Enable Redis to Start at Boot: To ensure Redis starts automatically at boot, enable the service:
sudo systemctl enable redis-server
-
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
- 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.