N
N
Nikolay2022-03-09 22:18:41
Laravel
Nikolay, 2022-03-09 22:18:41

How to manage user sessions in Laravel using Redis?

This is my first experience with Redis, so I might be missing something very simple

. Hi! The documentation states that you can work with sessions through session()or Request.

When the sessions were in MySQL, to get all user sessions it was enough to do this:
$sessions = request()->user()->sessions()->get();

When sessions are stored in Redis, the query above gives an error:

SQLSTATE[42S02]: Base table or view not found: 1146


Judging by
Illuminate\Support\Facades\Redis::connection('session')->keys('*')
- sessions work, in
phpRedisAdmin - there is also a table with user data, but for some reason it is called project_database_project_ cache I added one more connection :

config/database.phpsession
The code

'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'predis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', 0),
        ],

        'cache' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CACHE_DB', 1),
        ],

        'session' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_SESSION_DB', 2),
        ],

    ],

.envI added a variable to the file and SESSION_CONNECTION=sessionWhat REDIS_PASSWORD=password

was done:
php artisan optimize:clear
php artisan clear-compiled
composer dump-autoload
reboot

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Samuel_Leonardo, 2022-03-09
@iNickolay

The Redis driver does not offer the same flexibility as the database
If you can select any field from the database,
then in Redis you have a key => value,
while the key name has nothing to do with the user id
, of course you can take everything sessions from the radish and iterate over them with the appropriate time costs, a
separate connection is made so that the sessions are not mixed with the cache,

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question