i am trying to hook to the login even in my L5 app to set last login time and IP address. i can make it work with the following:
Event::listen(\'auth.login\'
Usually you can achieve by doing like this step by step for User Login Logs
first, you should have Auth Scaffolding
located the login and logout event at :
vendor\laravel\framework\src\Illuminate\Auth\Events
EventServiceProvider.php
protected $listen = [
'Illuminate\Auth\Events\Login' => [
'App\Listeners\LoginLogs',
],
'Illuminate\Auth\Events\Logout' => [
'App\Listeners\LogoutLogs',
],
];
public function boot()
{
parent::boot();
}
command: php artisan make:migration create_UserLoginHistory
Migration File
public function up()
{
Schema::create('tbl_user_login_history', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->datetime('login_at')->nullable();
$table->datetime('logout_at')->nullable();
$table->string('login_ip')->nullable();
$table->string('role');
$table->string('session_id');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('tbl_user_login_history');
}
then your Model : UserLoginHistory
public $timestamps = false;
protected $table = 'tbl_user_login_history';
protected $fillable = ['user_id','login_at','logout_at','login_ip','role','session_id'];
public function setLogOutLog(){
$this->where('session_id',request()->session()->getId())->update([
'logout_at' =>Carbon::now(),
]);
}
public function setLogInLog(){
$this->insert(
['user_id' => Auth::user()->id,'login_at' =>Carbon::now(),
'login_ip'=>request()->getClientIp(),'role' =>Auth::user()->role,
'session_id'=>request()->session()->getId()
]);
}
4.after the migration and model creation procedure, let's assume that you have already in roles in users table
Listener : LoginLogs Class
use App\UserLoginHistory;
private $UserLoginHistory;
public function __construct(UserLoginHistory $UserLoginHistory)
{
// the initialization of private $UserLoginHistory;
$this->UserLoginHistory = $UserLoginHistory;
}
public function handle(Login $event)
{
// from model UserLoginHistory
$this->UserLoginHistory->setLogInLog();
}
Listener : LogoutLogs Class
private $UserLogoutHistory;
public function __construct(UserLoginHistory $UserLoginHistory)
{
// the initialization of private $UserLogoutHistory;
$this->UserLogoutHistory = $UserLoginHistory;
}
public function handle(Logout $event)
{
// from model UserLoginHistory
$this->UserLogoutHistory->setLogOutLog();
}
after you do this all steps , try to login with Auth