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.