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

kestrelhawk's avatar

Remove / Merge Session After Subsequent Login

Hey All,

I'm currently building a project with Laravel 5.1, and there exists a page where users can see which other users are currently online, provided they have been active for the last 10 minutes; so far, this works well. This was achieved by writing user sessions to the database, through which I've also created an additional 'user_id' field in the sessions table that associates each session with the user's corresponding id.

However, if a user signs in from more than one location within that 10 minute period of being active, the user will appear in the table of online users multiple times, which is equal to the amount of sessions that currently exist in the 'sessions' table for that user.

That being said, is there any way in Laravel through which I can either merge (or refer back to) an existing session if the user signs in through another browser, or equally, delete the existing session on log in (I believe this may be more difficult to implement).

Moreover, are there any guidelines or best practices on handling what I'd like to achieve above? I would like to move forward with the cleanest solution possible :)

Thank you!

0 likes
4 replies
pmall's avatar

So select the online users in the table users from their last activity

kestrelhawk's avatar

@pmall Thanks for the response. I have already had success creating the query to obtain all users from the 'sessions' table based on their 'last_activity' (600 seconds or less); however, the main issue I'm experiencing is that multiple sessions are being created when a user signs in from multiple locations, which causes duplicate entries in the list of online users due to multiple sessions existing in the 'sessions' table.

Where I understand it's expected behaviour for multiple entries to appear in the 'sessions' table for each user, I would like to limit this to one session per user. Is this possible, or are there any best practices that I'm overlooking here?

pmall's avatar

You just said you update the user model with their last activity on every request. So select your online users from the users table, not the session table.

$online_users = User::where('last_activity', '>', now() - 10min)->get();

Why do you want to get this from the session table ?


Or another idea :

$online_users = User::select('users.*')
    ->join('sessions', 'sessions.user_id', '=', 'users.id')
    ->where('sessions.last_activity', '>', now() - 10min)
    ->groupBy('users.id')
    ->get();

Please or to participate in this conversation.