用户使用Laravel成功登录后,如何更新最后登录栏? [英] How to update the last login column when the user successful login with Laravel?
问题描述
当用户成功登录时,我尝试更新最后一个登录列,我尝试将下面的代码放在LoginController中,但没有用,我也尝试了一个监听器,遵循
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()]);
我的laravel版本是5.4.12.我该如何运作?
My laravel version is 5.4.12. How can I get it working?
推荐答案
您可以订阅在用户成功通过身份验证后触发的Login
事件.
You can subscribe to the Login
event fired after a user has been successfully authenticated.
在app/providers/EventServiceProvider.php
中,将事件和侦听器添加到$listen
数组.
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,
],
// ...
];
在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()]);
}
}
这篇关于用户使用Laravel成功登录后,如何更新最后登录栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!