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.
$table->timestamp('latest_login')->nullable(); $table->timestamp('previous_visit')->nullable();
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’.
protected $dates = [ 'created_at', 'updated_at', 'latest_login', 'previous_visit' ];
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:
'Illuminate\Auth\Events\Login' => [ 'App\Listeners\Users\LatestLogin', ], 'Illuminate\Auth\Events\Logout' => [ 'App\Listeners\Users\PreviousLogin', ],
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.
public function handle(Login $event) { $event->user->latest_login = Carbon::now(); $event->user->save(); }
public function handle(Logout $event) { $event->user->previous_visit = Carbon::now(); $event->user->save(); }
I also added:
use Carbon\Carbon;
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:
{{ $user->latest_login->diffForHumans() }}
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:
Last Visit: {{ Auth::user()->previous_visit->diffForHumans() }}
It outputs something like: Last Visit: 2 days ago
That is about it. I hope this helps someone else out.
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?
No it is not picked up with this code.