2.14.2.6. Setting up Redis in Laravel
Important points:
- You can only connect to Redis on a hosting via a Unix socket.
- PECL extension is available by default on hosting PhpRedis... There is no need to install additional clients.
- The instructions describe a general way to configure Redis. It may not be suitable for sites where changes have been made to the functionality of working with Redis.
For settings Redis in Laravel do the following:
- Edit the file
.env
located in the root of the project:- Find the Redis config block:
REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379
- Replace the lines with the following:
REDIS_HOST=/home/example/.system/redis.sock REDIS_DB=0 REDIS_CACHE_DB=1 REDIS_PREFIX=doepref_
- In the line with the parameter
REDIS_HOST
insteadofexample
indicate hosting account namein which the site is hosted. - In parameters
REDIS_DB
andREDIS_CACHE_DB
provide a unique identifier for the Redis database. - In the parameter
REDIS_PREFIX
specify the required prefix.
- Edit the file
database.php
located in the directoryconfig/
:- Find the code for connecting to Redis in the file, it will start with
'redis' => [
... The connection setup should look something like this:'redis' => [ 'client' => env('REDIS_CLIENT', 'phpredis'), 'options' => [ 'cluster' => env('REDIS_CLUSTER', 'redis'), 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'), ], 'default' => [ 'host' => env('REDIS_HOST'), 'password' => env('REDIS_PASSWORD'), 'port' => env('REDIS_PORT'), 'database' => env('REDIS_DB', 0), ], 'cache' => [ 'host' => env('REDIS_HOST'), 'password' => env('REDIS_PASSWORD'), 'port' => env('REDIS_PORT'), 'database' => env('REDIS_CACHE_DB', 1), ], ],
- Check Redis is working. For the test, edit the file
web.php
located in the directoryroutes/
by adding the following code to it:Route::get('redis-test', function (){ if(!Redis::get('test_time')){ Redis::set('test_time', date(DATE_RFC822)); } return "Date inserted in database: ".Redis::get('test_time'); });
Open your project by link
http://example.com/redis-test
where instead ofexample.com
enter your domain name. After the transition, the time of the first access to this link should be displayed.
Attention!
Redis database id must be unique for everyone CMS and for different types of caching, so that there are no errors with the intersection of data from different services.