raphadko raphadko - 4 months ago 133
PHP Question

Laravel - Architecture on how to find out last login of user

I've been looking for a way to check when users have been active on my website. My first idea is to create a datetime field on the database called "last login", every time the user would log in, it would update.

Seems fine, but when a user has a 'keep me logged in' token, the session will remain active and he won't have to to through the login process for a while, compromising the accuracy of the active date (I might send an email "We miss you" when in reality he's an active user)

The other approach I thought was to have some key actions which would trigger the 'active' saving, but then again, the user could not do some of these actions, having the same problem.

Since I can't update the field in every user action for performance reasons, what would be a good approach for this? What do the pros use?

Edit: I know Laravel has some authentication classes; do any of these functions activate when the user comes back (even if he is still logged in)?

Answer

You can listen on the auth.login event that is triggered for login with both credentials and remember me token. Once it's fired, you'd need to update the last login date.

First, create the listener:

class UpdateLastLoginDate {
  public function handle($user) {
    $user->last_login_at = Carbon::now();
    $user->save();
  }
}

Then register the listener in your EventServiceProvider:

protected $listen = [
  'auth.login' => [
        UpdateLastLoginDate::class
    ]
];

Update Since version 5.2, you must add the Event class name as the array key, and access the user as a property of the event object passed:

protected $listen = [
  'Illuminate\Auth\Events\Login' => [
        UpdateLastLoginDate::class
    ]
];


class UpdateLastLoginDate {
  public function handle($event) {
    $user = $event->user;
    $user->last_login_at = Carbon::now();
    $user->save();
  }
}

https://laravel.com/docs/5.2/upgrade (scroll to events)