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?
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()]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With