Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I use environment variables to configure Redis in Laravel Sail


Can I use environment variables to configure Redis in Laravel Sail


Yes, you can use environment variables to configure Redis in Laravel Sail. Here's how you can do it:

1. Set the Redis-related environment variables in your `.env` file:


   REDIS_HOST=redis
   REDIS_PASSWORD=null
   REDIS_PORT=6379
   

In this example, we're setting the Redis host to `redis` (the service name defined in the `docker-compose.yml` file), the password to `null`, and the port to `6379`.

2. Update the `config/database.php` configuration file to use the environment variables:

php
   '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'),
           'password' => env('REDIS_PASSWORD'),
           'port' => env('REDIS_PORT'),
           'database' => env('REDIS_DB', '0'),
       ],
   ],
   

This configuration will use the environment variables you set in the `.env` file to connect to Redis.

3. Ensure that the Redis service is defined in your `docker-compose.yml` file:

yaml
   redis:
     image: 'redis:alpine'
     ports:
       - '${FORWARD_REDIS_PORT:-6379}:6379'
     volumes:
       - 'sailredis:/data'
   

This defines the Redis service with the necessary configuration.

4. Start or restart your Sail environment:


   sail up -d
   

This will start the Redis service along with the other services defined in your `docker-compose.yml` file.

By using environment variables to configure Redis in Laravel Sail, you can easily manage the Redis connection details without hardcoding them in your application code. This makes it more flexible and easier to maintain across different environments.

Remember to ensure that the Redis service is properly defined in your `docker-compose.yml` file and that the environment variables match the configuration in your `config/database.php` file.

Citations:
[1] https://laravel.com/docs/11.x/redis
[2] https://github.com/laravel/sail/issues/591
[3] https://github.com/laravel/sail/issues/589
[4] https://laracasts.com/discuss/channels/guides/redis-horizon-with-sail
[5] https://stackoverflow.com/questions/67097278/add-new-service-using-laravel-sail