Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

likvidatorTM's avatar

Set session user from redis.

Hi! When user's action must be authorized laravel does request like this:

SELECT * FROM `users` WHERE `id` =   LIMIT 1

I want avoid it and cache this request in redis but i not understand how.

0 likes
3 replies
robrogers3's avatar
Level 37

This is difficult because the authorization for an action uses the same UserProvider as the rest of the app. It's the EloquentUserProvider

this is used for logging in. etc.

so, when the authorize method is called it uses the same method for looking up the user for a login. select * from users.

i'm guessing you want to keep all the convinces of the EloquentUserProvider except for this cause it's slow.

So your solution is probably to Write your own Custom UserProvider.

it's not that hard, what you need to do is extend the EloquentUserProvider and override the retriveById method()

In this method try redis first, then fall back to the db.

here's step by step https://laravel.io/forum/11-04-2014-laravel-5-how-do-i-create-a-custom-auth-in-laravel-5

Here's what your interested in:

public function retrieveById($identifier)
    {
    if ($user = $this->findUserInRedis($identifier)) {
        return $user;
}

            $model = $this->createModel();

        return $model->newQuery()
            ->where($model->getAuthIdentifierName(), $identifier)
            ->first();  
    }

public function findUserInRedis($identfier) {
    Cache::get()
}

you may also want to override:

public function retrieveByCredentials so you can put the user in the cache when they login. (how else can you look them up in redis

There's a lot more you need to figure out. Like how long are they in redis? How do purge them on logout etc.

2 likes
likvidatorTM's avatar

Yes, i looked sources and find this method but i thought that this isn't better way

robrogers3's avatar

well if you find it let us know cause I'd like to know.

1 like

Please or to participate in this conversation.