Here is sample code to integrate Redis with Laravel:
Install Redis and Predis
First, install the Redis server on your system and the Predis library in your Laravel project:
bash
composer require predis/predis
Configure Redis Connection
In your `config/database.php` file, configure the Redis connection details:
php
'redis' => [
'client' => env('REDIS_CLIENT', 'predis'),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 0),
],
],
Use Redis Facade
In your Laravel code, you can use the `Redis` facade to interact with Redis. For example, to set and retrieve a key-value pair:
php
use Illuminate\Support\Facades\Redis;
Redis::set('name', 'Taylor');
$value = Redis::get('name');
You can call any Redis command on the `Redis` facade and it will be passed directly to Redis[1][2][3].
Caching with Redis
To use Redis as a cache driver in Laravel, update the `CACHE_DRIVER` environment variable to `redis` in your `.env` file[4].
Then in your code, you can use the `Cache` facade to store and retrieve cached values:
php
use Illuminate\Support\Facades\Cache;
Cache::put('key', 'value', 60); // cache for 60 seconds
$value = Cache::get('key');
Pub/Sub with Redis
Laravel provides a convenient interface to the Redis publish and subscribe commands using the `Redis` facade[2][3]:
php
Redis::subscribe(['messages'], function($message) {
echo $message;
});
Redis::publish('messages', json_encode(['foo' => 'bar']));
This allows you to build real-time features like chat, notifications, and more.
By leveraging Redis's speed and data structures, you can significantly boost the performance and scalability of your Laravel application[1][4].
Citations:[1] https://aglowiditsolutions.com/blog/laravel-redis/
[2] https://laravel.com/docs/11.x/redis
[3] https://laravel.com/docs/5.3/redis
[4] https://bagisto.com/en/how-to-use-redis-with-laravel/
[5] https://www.honeybadger.io/blog/laravel-caching-redis/