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

Deveasey's avatar

How to get Latest User session

Working on Laravel 10 using default Session table Goal or expected outcome: i need to know when a user last interacted with the site. So getting the session with the most recent "last_activity" timestamp is my first step.

Session model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Session extends Model
{
    protected static function booted(): void
    {
        static::addGlobalScope('last_activity_datetime', function (Builder $builder) {
            $builder->selectRaw('*, FROM_UNIXTIME(last_activity) as last_activity_datetime');
        });
    }
}

i was thinking something like the following

auth()->user()->sessions()->latest('last_activity')->first()

This seems like it should be obvious but i cant seem to find a solution

0 likes
10 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To achieve the goal of getting the session with the most recent "last_activity" timestamp for a user, you can use the orderBy method to sort the sessions by last_activity in descending order and then get the first result. Assuming that you have a relationship set up between your User model and the Session model, your code could look something like this:

$latestSession = auth()->user()->sessions()->orderBy('last_activity', 'desc')->first();

However, if you haven't set up a relationship between the User model and the Session model, you would need to query the Session model directly, filtering by the user ID. Here's how you could do it:

use App\Models\Session;

// Assuming you have the user ID
$userId = auth()->id();

$latestSession = Session::where('user_id', $userId)
                        ->orderBy('last_activity', 'desc')
                        ->first();

This will give you the latest session for the authenticated user based on the last_activity timestamp. If you want to include the last_activity_datetime attribute that you've added in the global scope, make sure that the Session model is using the last_activity column as a Unix timestamp. If it's already a datetime column in the database, you wouldn't need to convert it using FROM_UNIXTIME.

Remember to replace user_id with the actual column name in your sessions table that references the user's ID.

Deveasey's avatar
auth()->user()->sessions()->orderBy('last_activity', 'desc')->first()

seems to be doing the trick....

Snapey's avatar

invalid sessions (ones that have timed out) are randomly cleaned so I doubt this would be a reliable solution.

Of course getting the most recent session will give you a record but it does not seem to match your requirements of when was the user last on the site?

If you are happy with getting the most recent session, how is this any different to just getting the current timestamp ?

1 like
Deveasey's avatar

@Snapey I need to build a service that will find all users that have not been active in the past x number of days. Are you saying Laravel will automatically delete old records for any session that has expired?

1 like
gych's avatar

I use middleware for this I've added an example below. For this to work you'll have to add last_seen timestamp column to the users table.

This will update the last_seen value each time a user visits a web route. You can even customize this a bit and add extra 5 minutes to it, keeping in mind that the user will stay a bit longer on the page after visiting the route.

Create new middleware for example LastSeenUserActivity

class LastSeenUserActivity
{
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
				User::where('id', Auth::user()->id)->update(['last_seen' => Carbon::now()]);
		}
        return $next($request);
    }
}

Then add this middleware to Kernel.php web middleware group

    protected $middlewareGroups = [
        'web' => [
        	// Your other already existing middlewares in the web middleware group
            \App\Http\Middleware\LastSeenUserActivity::class,
        ],

		// Rest of the of your code
2 likes
Deveasey's avatar

@gych I see. Why did you not use sessions last_activity? I'm only looking for activity in the last 90 days.

gych's avatar

@Deveasey Laravel randomly removes old sessions via garbage collector, therefore using this is not reliable.

If you use the approach/example that I showed, you can filter the users based on last_seen and only get results for the dates that are not older than 90 days.

1 like

Please or to participate in this conversation.