Redis Laravel How to use

Learn how to use Redis to boost Laravel performance with a quick example.

Using Redis with Laravel

Laravel provides an expressive, unified API for various caching backends. Redis is an open source, in-memory data structure store that can be used as a database, cache, and message broker. It's an ideal choice for Laravel applications which need high performance and great scalability. In this tutorial, we will show you how to use Redis to store and retrieve data from a Laravel application.

Installing Redis

Before we can use Redis with Laravel, we need to install Redis on our system.
$ sudo apt-get install redis-server
$ sudo systemctl enable redis-server.service
$ sudo systemctl start redis-server.service
Once Redis is installed, we can open the Redis configuration file and make any necessary changes.

Configuring Redis

In order to use Redis with our Laravel application, we need to configure Redis in our application's .env file. We can add the following lines to our .env file:
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
The REDIS_HOST variable specifies the hostname or IP address of the Redis server. The REDIS_PASSWORD variable specifies the password used to authenticate to the Redis server. The REDIS_PORT variable specifies the port used to connect to the Redis server.

Using Redis with Laravel

Once Redis is installed and configured, we can start using it with our Laravel application. We can use the Redis facade to interact with Redis. For example, we can use the Redis facade to store and retrieve data from the Redis server.
// Set a value in Redis
Redis::set('key', 'value');

// Retrieve the value from Redis
$value = Redis::get('key');

// Delete the value from Redis
Redis::del('key');
We can also use Redis to store complex data structures like hashes, lists, and sets.
// Store a hash in Redis
Redis::hmset('user:1', [
    'name' => 'John Doe',
    'email' => '[email protected]'
]);

// Retrieve a hash from Redis
$user = Redis::hgetall('user:1');
We can also use Redis to store lists and sets.
// Store a list in Redis
Redis::lpush('users', ['John', 'Jane', 'Bob']);

// Retrieve a list from Redis
$users = Redis::lrange('users', 0, -1);

// Store a set in Redis
Redis::sadd('user_ids', [1, 2, 3]);

// Retrieve a set from Redis
$user_ids = Redis::smembers('user_ids');
Redis also provides a publish-subscribe messaging system which can be used to send messages from one application to another.
// Publish a message
Redis::publish('user.created', 'User John was created');

// Subscribe to a channel
Redis::subscribe(['user.created'], function ($message) {
    // do something with the message
});
Redis is a powerful and versatile tool that can be used to store and retrieve data from a Laravel application. It's an ideal choice for applications which need high performance and great scalability.

Answers (0)