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
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. 😀😀
Top comments (5)
Don't miss to add 'last_login_at' and 'last_login_ip_address' to the $fillable array in your user model: App\Models\User;
I needed to Carbon::parse last_login_at to use diffForHumans in my view:
You can cast column 'last_login_at' to datetime on User model
Thank you for the suggestion, yes we can do that way too.
Couple things on this:
I think
$table->timestamp('last_login_at')
should be$table->dateTime('last_login_at')
to work with thenow()
function.$table->timestamp('last_login_ip_address')
should be$table->string('last_login_ip_address')
Definitely points in the right direction though.
Thank you for your thoughts, I appreciate you suggestion.