在数据库中,我有一个表last_login_at列的用户。每当某个用户登录时 - 我想要上传 last_login_at 。
所以,我创建了app / Listeners / UpdateLastLoginOnLogin.php :
protected $listen = [
'auth.login' => [
'App\Listeners\UpdateLastLoginOnLogin',
],
];
在app / Providers / EventServiceProvider中:
use Illuminate\Auth\Events\Login;
class UpdateLastLoginOnLogin
{
public function handle(Login $event)
{
$event->user->last_login_at = Carbon::now();
$event->user->save();
}
}
但这不起作用,事件未得到处理。这里已经提到了同样的问题:EventServiceProvider mapping for Laravel 5.2 login但没有解决方案。我试过这样做:
...
protected $listen = [
'Illuminate\Auth\Events\Login' => [
'App\Listeners\UpdateLastLoginOnLogin',
],
];
和
<parent-elem>
<child-elem></child-elem>
</parent-elem>
但它没有用。
另外,我检查了这个:https://laracasts.com/discuss/channels/general-discussion/login-event-handling-in-laravel-5但 php artiasn clear-compiled 并没有解决问题。
编辑:其他详细信息,此处有关项目的链接实际上完全相同(以相同的方式完成):https://github.com/tutsplus/build-a-cms-with-laravel
答案 0 :(得分:12)
You are almost there, just a few changes more, Events and Listeners for authentication have changed a little in Laravel 5.2: the handle method in UpdateLastLoginOnLogin should have just an event as parameter
namespace App\Listeners;
use Carbon\Carbon;
use Auth;
class UpdateLastLoginOnLogin
{
public function handle($event)
{
$user = Auth::user();
$user->last_login_at = Carbon::now();
$user->save();
}
}
And for the EventServiceProvider you specify the listeners like this :
protected $listen = [
'Illuminate\Auth\Events\Login' => [
'App\Listeners\UpdateLastLoginOnLogin@handle',
],
];