Get Last Login Info of user in laravel

Snehal Rajeev Moon - Sep 10 '21 - - Dev Community

Hello, in some of the cases we require to track the user's last login activity into our site for that we need to save there login details into our database. Login details can contains last login date/time, location, IP address and more.

So, in this blog we are going to save user's last login and its IP address into our database.

Steps to follow -
  • Create Migrations
  • Register Event/Listener
  • Save/Display Last login info

First create a migration files:

php artisan make:migration add_last_login_at_column_to_users_table
php artisan make:migration add_last_login_ip_address_column_to_users_table
Enter fullscreen mode Exit fullscreen mode

Write the below code in migration file

  • for last login field
    $table->timestamp('last_login_at')->nullable();

  • for last last_login_ip_address field
    $table->timestamp('last_login_ip_address')->after('last_login_at')->nullable();

I am using Laravel default scaffolding which gives us login and registration blade.

Go to the Laravel documentation and search Authentication in that go to Event you will see the Login Event/Listener

'Illuminate\Auth\Events\Login' => [
        'App\Listeners\LogSuccessfulLogin',
    ],
Enter fullscreen mode Exit fullscreen mode

We are going to create our own Listener, so that when user logged in we will save its login details. Register this Event in EventServiceProvider into $listen event listener mapping.

protected $listen = [
 'Illuminate\Auth\Events\Login' => [
        'App\Listeners\UserLoginAt',
  ],
]
Enter fullscreen mode Exit fullscreen mode

After that run this command: It will create Listener file UserLoginAt.

php artisan event:generate
Enter fullscreen mode Exit fullscreen mode

Open UserLoginAt listener file and in handle method write the below code.

use Carbon\Carbon;

public function handle(Login $event)
{
    $event->user->update([
       'last_login_at => Carbon::now(),
       'last_login_ip_address' => request()->getClientIp()
    ]);
}
Enter fullscreen mode Exit fullscreen mode

This is the simple code we require to store user login details into our database.

Now we can access this information anywhere into our project, by using below code. I am accessing it in dashboard.blade.php file

{{ auth()->user()->last_login_at->diffForHumans() }}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading. 😀😀

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .