jonprasetyo jonprasetyo - 4 years ago 287
PHP Question

Laravel - last login date and time timestamp

I know there are fields automatically inserted (updated_at and created_at) but I was wondering if there is like a timestamp Eloquent method or the Laravel way to produce timestamps.

For instance I want to timestamp every time a user logs in to my system and store it into the database. - this we can see each user's last login date and time details.

Many thanks!

Answer Source

You may observe the auth.login event and update the user's last login time. See the first example in the documentation for events to accomplish exactly what you're trying to do.

Event::listen('auth.login', function($user) {
    $user->last_login = new DateTime;

    $user->save();
});

Note: In 4.0, the event name is user.login. In 4.1, the event name is auth.login

Update

It's really up to you where you put your Event listeners. If you read the linked to doc page, it states:

So, you know how to register events, but you may be wondering where to register them. Don't worry, this is a common question. Unfortunately, it's a hard question to answer because you can register an event almost anywhere! But, here are some tips. Again, like most other bootstrapping code, you may register events in one of your start files such as app/start/global.php.

If your start files are getting too crowded, you could create a separate app/events.php file that is included from a start file. This is a simple solution that keeps your event registration cleanly separated from the rest of your bootstrapping. If you prefer a class based approach, you may register your events in a service provider. Since none of these approaches is inherently "correct", choose an approach you feel comfortable with based on the size of your application.

My personal preference would be to register them within a Service Provider, since that would keep them segregated and to me is the more 'Laravel' way of doing things. If you need help with service providers, see this documentation entry.

However, if you really just want to get something up and running as quickly as possible, it would be just as easy for you to register that listener inside of app/start/global.php

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download