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

I was looking for a way to check when users were active on my site. My first idea is to create a datetime field in a database called last login, every time a user logs in, it will be updated.

Everything seems to be fine, but when the user has the 'keep me logged' token, the session will remain active and he will not have to go through the login process for a while, violating the accuracy of the active date (I can send an email β€œWe miss you” when in fact he is an active user)

Another approach, which, as I thought, was to have some key actions that cause an β€œactive” save, but again, the user would not be able to perform some of these actions having the same problem.

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

Edit: I know that Laravel has authentication classes; Does any of these functions activate when the user returns (even if he is still logged in)?

+5
source share
1 answer

You can listen to the auth.login event, which is fired to log in using both credentials and remember me . After starting it, you will need to update the last login date.

First create a listener:

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

Then register the listener in EventServiceProvider :

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

Update Starting with version 5.2, you should add the name of the Event class as an array key and access the user as a property of the passed event object:

 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)

+8
source

All Articles