Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update the last login column when the user successful login with Laravel?

Tags:

php

laravel

I'm trying to update the last login column when the user successful login, I tried putting the code below in LoginController, but it didn't work, I've tried with a listener too, following this answer, but it didn't work, nothing ever happened, seems like the listener wasn't being executed.

        DB::table('users')
              ->where('id', Auth::id())
              ->update(['lastlogin' => Carbon::now()]);

My laravel version is 5.4.12. How can I get it working?

like image 205
Antonio Avatar asked Dec 06 '22 15:12

Antonio


1 Answers

You can subscribe to the Login event fired after a user has been successfully authenticated.

In app/providers/EventServiceProvider.php, add the event and listener to the $listen array.

protected $listen = [
    // ...
    \Illuminate\Auth\Events\Login::class => [
        \App\Listeners\LastLogin::class,
    ],
    // ...
];

Create a new event listener in app/listeners/LastLogin.php

namespace App\Listeners;

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Auth\Events\Login;

class LastLogin
{
    /**
     * Handle the event.
     *
     * @param  \Illuminate\Auth\Events\Login $event
     * @return void
     */
    public function handle(Login $event)
    {
        // Update user last login date/time
        $event->user->update(['lastlogin' => Carbon::now()]);
    }
}
like image 103
fubar Avatar answered Jan 18 '23 22:01

fubar