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

vinodjoshi's avatar

laravel session with database driver how to insert user_id field value in session table

Hi

I am using Laravel 5.5 and storing session in database table name with session.

Schema::create('sessions', function (Blueprint $table) {
        $table->string('id')->unique();
        $table->unsignedInteger('user_id')->nullable();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->text('payload');
        $table->integer('last_activity');
    });

Now when i start using application everything works fine.

But when i logged in to application then user_id field is still null. Is there any other way to insert logged in user's id to it ?

My end goal is to check how many users are logged in to application on current time.

Am i doing proper way to get my result or is there any other way to do same.

0 likes
8 replies
Cronix's avatar

Just adding it in the migration (creating the field in the table) isn't going to populate it. You'd need to add it into the session driver as well so it would write a value when the session is created. However, every visitor gets a session, not just logged in users, so this wouldn't work very well since there wouldn't be a user_id for users who aren't logged in.

It would be better to remove that user_id, and just query the session table directly for sessions where last_activity is within some time range, like within the last 5 or 10 minutes. That would give you how many users are logged in to application on current time

vinodjoshi's avatar

@Cronix Thanks for your Reply i think you are right user_id doesn't make sense if there are request without logged in users.

I had taken that user_id field because to query directly on last_activity and then get count of that user_id, so it can't slow down the query at least as per my knowledge.

I have done something like this

$currentTimestamp = time(); $backTimestamp = strtotime("-10 minutes");

    $SessionModel = SessionModel::where('last_activity','>',$backTimestamp)->get()->toArray();
    $onlieUsers = 0;
    foreach ($SessionModel as $key => $value) {
        $payload =  unserialize(base64_decode($value['payload']));

        if(isset($payload['login_cpd-user_59ba36addc2b2f9401580f014c7f58ea4e30989d']))
        {
            $onlieUsers = $onlieUsers+1;
        }
        
    }

Is above code perfect to fetch count of online users Or do you have any optimize way to get this count.

Thanks again

Cronix's avatar

I don't know what this is, or how it's set...

if(isset($payload['login_cpd-user_59ba36addc2b2f9401580f014c7f58ea4e30989d']))
        {
            $onlieUsers = $onlieUsers+1;
        }

Why are you only counting those as users?

$recentTime = Carbon\Carbon::parse('-10 minutes');
$onlineUsers = SessionModel::where('last_activity','>',$recentTime)->count();
vinodjoshi's avatar

Sorry i forgot to explain before I have multiple authentication in application.

Using Laravel 5.5, Session Driver Database

One authentication user's id is stored in this key when i decode and unserialize the payload.

Cronix's avatar

Well, if it works for you! Does it?

vinodjoshi's avatar

Yes, i think so. till now its working perfect.

If you have any other way then let me know or Do you have found any glitch to above code then suggestion is most welcome.

one more thing above code is for logged in users count.

Cronix's avatar

It looks ok. If you have a lot of visitors, you might consider caching that result for 10 minutes so you're not hitting the db and going through that loop each time you need the data. It's kind of an expensive thing to do with all of the decoding and checking values. https://laravel.com/docs/5.6/cache

vinodjoshi's avatar

Yes you are right, i need to cache results. Thanks for suggestion, .

Apart From this session with Database Driver any other way to get this logged In user's count.

So i can differentiate the ways and pick best way for this functionality in future.

Thanks again for your advise.

Please or to participate in this conversation.