Laravel 5.2 Login Event Handling

别来无恙 提交于 2019-12-10 20:51:28

问题


In the database I have a table users with column last_login_at. Everytime when some user logs in - I want to uptade last_login_at.

So, I created app/Listeners/UpdateLastLoginOnLogin.php:

namespace App\Listeners;

use Carbon\Carbon;

class UpdateLastLoginOnLogin
{
    public function handle($user, $remember)
    {
        $user->last_login_at = Carbon::now();

        $user->save();
    }
}

In app/Providers/EventServiceProvider:

    protected $listen = [
        'auth.login' => [
            'App\Listeners\UpdateLastLoginOnLogin',
        ],
    ];

BUT this doesn't work, event is not handled. The same problem has already been mentioned here: EventServiceProvider mapping for Laravel 5.2 login but without solution. I have tried to do like this:

...

use Illuminate\Auth\Events\Login;

class UpdateLastLoginOnLogin
{
    public function handle(Login $event)
    {
        $event->user->last_login_at = Carbon::now();
        $event->user->save();
    }
}

and:

protected $listen = [
    'Illuminate\Auth\Events\Login' => [
        'App\Listeners\UpdateLastLoginOnLogin',
    ],
];

But it doesn't work.

Also, I checked this: https://laracasts.com/discuss/channels/general-discussion/login-event-handling-in-laravel-5 but php artiasn clear-compiled didn't solve the problem.

EDIT: FOR OTHER DETAILS, HERE'S A LINK TO THE PROJECT which is actually exactly the same (it is done in the same way): https://github.com/tutsplus/build-a-cms-with-laravel


回答1:


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',
    ],
];


来源:https://stackoverflow.com/questions/35295062/laravel-5-2-login-event-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!