Get the last login date of a user in Laravel
Sponsored by
unolia.comAll your domains in one place. Helps you find problems, gives you performance and security insights!
Want to sponsor this blog ?
Contact me or use
Github sponsor
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:
php artisan make:listener UpdateUserLastLoggedAt --event=Illuminate\Auth\Events\Login
And then implement the listener as follows:
<?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:
php artisan make:migration add_last_logged_at_to_users_table
Then, in the migration file, you can add the new column:
Schema::table('users', function (Blueprint $table) { $table->timestamp('last_logged_at')->nullable();});
And run the migration:
php artisan migrate
Some notes
- The
last_logged_at
field is nullable, so it will benull
for users who have never logged in. - The
UpdateUserLastLoggedAt
listener implements theShouldQueue
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