Index

Get the last login date of a user in Laravel

Published

Tags

#laravel

By default, in Laravel, the last_login_at field is not available in the users table. I personally needed this information to run some background tasks.

The approach I chose is to use the Login event provided by Laravel Fortify.

For that, just create a new listener that will update the last_logged_at field in the users table whenever a user logs in.

The code

You can create a listener using the Artisan command:

Copied!
php artisan make:listener UpdateUserLastLoggedAt --event=Illuminate\Auth\Events\Login

And then implement the listener as follows:

Copied!
<?php
 
namespace App\Listeners...
 
use App\Models\User;
use Illuminate\Auth\Events\Login;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue
 
class UpdateUserLastLoggedAt implements ShouldQueue
{
use InteractsWithQueue;
 
public function __construct() {}
 
public function handle(Login $event): void
{
/** @var User $user */
$user = $event->user;
 
$user->update([
'last_logged_at' => now(),
]);
}
}

By default, Laravel will automatically find and register your event listeners by scanning your application's Listeners directory. When Laravel finds any listener class method that begins with handle or __invoke, Laravel will register those methods as event listeners for the event that is type-hinted in the method's signature.

— https://laravel.com/docs/12.x/events#defining-listeners

Oh and don't forget to add the last_logged_at field to your users table migration:

Copied!
php artisan make:migration add_last_logged_at_to_users_table

Then, in the migration file, you can add the new column:

Copied!
Schema::table('users', function (Blueprint $table) {
$table->timestamp('last_logged_at')->nullable();
});

And run the migration:

Copied!
php artisan migrate

Some notes

  • The last_logged_at field is nullable, so it will be null for users who have never logged in.
  • The UpdateUserLastLoggedAt listener implements the ShouldQueue interface, which means it will be queued for processing. This is preferable if you want to avoid slowing down the login process.
  • This works with Breeze, Jetstream, and Sanctum as they all use the Illuminate\Auth\Events\Login event.
  • If you wanna go further, the Login event also provides the following properties:
    • string $guard – The authentication guard name.
    • Authenticatable $user – The authenticated user.
    • bool $remember – Indicates if the user should be "remembered".

Syntax highlighting provided by torchlight.dev.

Discussion on Bluesky

likes
reposts
comments

Comments

Reply on Bluesky to join the conversation.