Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 10, 2021 06:55 pm GMT

Get Last Login Info of user in laravel

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_tablephp artisan make:migration add_last_login_ip_address_column_to_users_table

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',    ],

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',  ],]

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

php artisan event:generate

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()    ]);}

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() }}

Thank you for reading.


Original Link: https://dev.to/snehalk/get-last-login-of-user-in-laravel-ckg

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To