laravel 5中的登录事件处理 [英] login event handling in laravel 5

查看:67
本文介绍了laravel 5中的登录事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使在我的L5应用程序中,我也试图连接到登录名,以设置上次登录时间和IP地址.我可以通过以下方法使其工作:

i am trying to hook to the login even in my L5 app to set last login time and IP address. i can make it work with the following:

Event::listen('auth.login', function($event)
{
    Auth::user()->last_login = new DateTime;
    Auth::user()->last_login_ip = Request::getClientIp();
    Auth::user()->save();
});

但是,我想知道在L5中做到这一点的最佳方法是使用事件处理程序对象.我尝试创建一个事件处理程序,并在事件服务提供程序中将auth.login添加为数组键,但是没有用.我不确定auth.login事件是否可行.如果不是,则将上面的代码放在最合适的位置.为了进行测试,我将其放在我的routes.php文件中,但是我知道那不是应该的.

however, i am wondering what the best way to do this in L5 is with the event handler object. i tried creating an event handler and adding auth.login as an array key in the events service provider, however that didnt work. im not sure if that is possible or not with the auth.login event. if it isnt, where is the most appropriate place to put the above code. for testing, i put it in my routes.php file, but i know that isnt where it should be.

推荐答案

仅适用于5.0.*和5.1.*.

有关5.2.*解决方案,请参见下面的JuLiAnc响应.

在处理了两个建议的答案以及更多的研究之后,我终于想出了我一开始尝试的方法.

after working with both proposed answers, and some more research i finally figured out how to do this the way i was trying at first.

我运行了以下工匠命令

$ php artisan handler:event AuthLoginEventHandler

然后,我更改了生成的类,删除了Event类的导入,并导入了用户模型.我还将User $user$remember传递给handle方法,因为当auth.login事件被触发时,那就是传递的内容.

Then i altered the generated class removing the import of the Event class and and imported the user model. I also passed User $user and $remember to the handle method since when the auth.login event is fired, thats what is passed.

<?php namespace App\Handlers\Events;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
use App\User;

class AuthLoginEventHandler {

    /**
     * Create the event handler.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  User $user
     * @param  $remember
     * @return void
     */
    public function handle(User $user, $remember)
    {
        dd("login fired and handled by class with User instance and remember variable");
    }

}

现在我打开EventServiceProvided.php并修改$listen数组,如下所示:

now i opened EventServiceProvided.php and modified the $listen array as follows:

protected $listen = [
    'auth.login' => [
        'App\Handlers\Events\AuthLoginEventHandler',
    ],
];

我意识到,如果一开始它不起作用,您可能需要

i realized if this doesn't work at first, you may need to

$ php artisan clear-compiled

我们去了!我们现在可以使用事件处理程序类通过auth.login事件响应用户登录了!

There we go! we can now respond to the user logging in via the auth.login event using an event handler class!

这篇关于laravel 5中的登录事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆