Laravel event handler for last login

I recently needed to show on the admin side of an app the last login of all users and if they had logged in at all.  I also wanted to show the user the last time that they visited the site.  I used event handlers for both these tasks.

Update the Users Table

I have used the user model to store a timestamp for each event, so I added two new rows to my users table.  I will then be able to access these easily in my blade template.

On the user model I also added both timestamps to the proteced $dates array. By doing this I will be able to use ‘Carbon’ helpers like ‘diffForHumans’.

Creating the Event Handlers:

On the admin side I used the login event and for the user I used the logout event to record the current time and date to the users table.

In the EventServiceProvider service provider (app/Providers/EventServiceProvider.php) I added the following to the $listen array:

I then ran php artisan event:generate. This command then creates two event listeners located at app\Listeners\Users\LatestLogin and app\Listeners\Users\PreviousLogin.

Each event listener’s handle()method I added the following.  

I also added:

to each listener.

Now when a user logs in or logs out the event listener fires and updates the appropriate row of the users table for the user.

Blade

Finally for completeness in my blade file I can call:

And it will output something like – 1 hour ago – or however long it was since the user signed in.

For the user in the view I add:

It outputs something like: Last Visit: 2 days ago

That is about it. I hope this helps someone else out.

2 thoughts on “Laravel event handler for last login

  1. A lovely and clean approach, this helps a lot.

    I built something similar for our application on BulkSMSNigeria.com but the approach wasn’t as clean as these. Moreso, I wasn’t tracking previous visits.

    I have a question though, in situations where the user fails to log out and his session expires will the previous visits still update? That is, does session expiration also trigger the logout event?

Leave a Reply

Your email address will not be published. Required fields are marked *