Laravel User Last Logged In

In this tutorial, we’re going to create a new Laravel listener that will listen to the user logged in event and then update the user record with the time they logged in.

This is a handy feature to check how often your users are logging in and which ones are most active in your application.

Laravel Events

Laravel has a built feature to create events in your application, this will allow you to run code based off different actions in your application.

If you’ve used WordPress before you can use this in a similar way to the action and filter hooks.

Laravel Events

You can create your own event by using the command php artisan make:event.

But it also comes with a few built in events that you can listen for and run new code.

The event we’re going to listen for is Illuminate\Auth\Events\Login which will run when the user logs into your application.

Add Last Logged In Column

First we need to a create a new column on the user database table, we can do this by creating a database migration script php artisan make:migration AddLastLoggedInDate.

This will create a file in database/migrations.

Inside this migration file there will be two functions up and down. In the up function we need to add the last_logged_in column to store the date time.

Then in the down function we need to remove the column.

Now when we run the command php artisan migrate we will have a new column on the users table.

Logged In Listener

With the new column created we can listen for the logged in event and save the current date time to the user column.

Inside your EventServiceProvider you'll need to register the new listener.

Now when we run the command php artisan event:generate Laravel will create the new listener file inside the Listener folder.

Inside the handle function we can now assign the current time to the new last_logged_in column and then update the user. When the user is logged in, the user object will be past into the Login event there we can access this from inside the listener.

Now whenever a user logs into your application we’ll store the last time that user was able to login.

Originally published at

Software Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store