沃梦达 / 编程问答 / php问题 / 正文

Laravel 5 中的登录事件处理

login event handling in laravel 5(Laravel 5 中的登录事件处理)

本文介绍了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 AppHandlersEvents;

use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldBeQueued;
use AppUser;

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

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

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 中的登录事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel 5 中的登录事件处理

基础教程推荐