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

eggplantSword's avatar

Custom Session Handler

I'm trying to save with the session the logged in user and since I have multiple guards it's not as simple as just a user_id, I did read up on this part of the docs https://laravel.com/docs/8.x/session#adding-custom-session-drivers

Now I'm not sure about the actual code that does in the write method, I did find this old answer https://laracasts.com/discuss/channels/laravel/how-to-store-users-id-in-session-table-laravel-5?page=1&replyId=86313

However this code doesn't work for me I get this error

Undefined property: App\Extensions\CustomSessionHandler::$exists

This is my code

public function write($id, $data)
    {
        $user_id = (auth()->check()) ? auth()->user()->id : null;
        $client_id = (Auth::guard('client')->check()) ? Auth::guard('client')->user()->id : null;

        if ($this->exists) {
            $this->getQuery()->where('id', $id)->update([
                'payload' => base64_encode($data), 'last_activity' => time(),
                'user_id' => $user_id, 'client_id' => $client_id
            ]);
        } else {
            $this->getQuery()->insert([
                'id' => $id, 'payload' => base64_encode($data), 'last_activity' => time(),
                'user_id' => $user_id, 'client_id' => $client_id
            ]);
        }

        $this->exists = true;
    }

How can I fix this to check the auth guard and if a client is logged in to save into client_id the client's id?

0 likes
2 replies
Brian Kidd's avatar

Hi @msslgomez , what is the relationship between a user and a client? Is there a client id on the users table?

eggplantSword's avatar

They're separate tables in the db, the users are like admins and the clients are well clients. They don't have a relationship.

Please or to participate in this conversation.