How to Save User’s Last Login Time and IP Address

Quick tip of the day. Default Laravel Auth comes with User table and model, but without logging capability, so we need to build it ourselves. Fortunately, it’s very easy, I will show you one method.

Let’s say that we want to save user’s last login time and IP address in the same users table.
So we start with database migration:

Then we fill it with these fields:

Next, we need to add these fields as fillables in app/User.php model:

Finally, how do we fill them in? You need to know that there is authenticated() method in the AuthenticatesUsers trait. It’s called every time someone logs in.

In trait this method is empty. So we have freedom to override it in LoginController and add whatever code we need.


And, that’s it! Here’s what we have in users table after log in:

laravel last login ip address

Want to generate Laravel adminpanel online?
You don't need any packages to do that!

12 thoughts on “How to Save User’s Last Login Time and IP Address

  1. What other things may be interesting to collect that you could collect on Login? I really like this! Thank you!

  2. When a password reset is performed the user is automatically logged in. This method is then not triggered. An event listener is maybe a better solution or what do you think?

    1. Hi Leslie, same thing about registering – user is automatically logged in and this event isn’t triggered. Perhaps you’re right, even listener somewhere “deeper” could be better but you need to know what events to listen to.

  3. I hope you guys noticed that the updated_at column gets the same value always as last_login_at column. It shouldn’t be so.

    1. updated_at column should be different to last_login_at when you change your password or another personal data under users table.

Leave a Reply

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