Search code examples
phplaravellaravel-5.5laravel-authentication

Laravel 5.5 : Last Login and Last Login IP are not to be updating on successful login


I am using laravel 5.5, want to record Last Login (date time)and Last Login IP on each successful login.but its not updating.

LoginController:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected function authenticated(Request $request, $user)
    {
        $user->update([
            'last_login_at' => Carbon::now()->toDateTimeString(),
            'last_login_ip' => $request->getClientIp()
        ]);
    }
}

User Model:

protected $fillable = [
    'first_name','last_name', 'email', 'password','phone','user_type','last_login_at',
    'last_login_ip',
];

Solution

  • Recording last login information is useful and you can easily save and update the last login time and IP address of the client.

    You can achieve this in several ways but I am gonna show you very simple and effective technique, just add the below-shown method to the login Controller

    function authenticated(Request $request, $user)
        {
            $user->last_login = Carbon::now()->toDateTimeString();
            $user->last_login_ip = $request->getClientIp();
            $user->save();
        }