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

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

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.

推荐答案

EDIT: this only works in 5.0.* and 5.1.*.

For the 5.2.* solution see JuLiAnc response below.

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.

我运行了以下 artisan 命令

$ php artisan handler:event AuthLoginEventHandler

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");
    }

}

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响应用户登录.使用事件处理程序类登录事件!

Laravel相关问答推荐

提交表格后如何在Livewire 3中调度模式窗口?

使用MAATWebSite/EXCEL导入Exel时,不会创建Laravel模型

如何定制有关密码被泄露的Laravel Breeze S消息?

Laravel Valet 安装后 Ping test.dev 返回未知主机

使用 Amazon S3 的 Storage::get() 返回 false

如何在 Laravel Passport 中获取刷新令牌?

如何在 laravel 5.2 中显示 500 内部服务器错误页面?

即使上传了文件,Laravel Input::hasFile('image') 也会返回 false

Laravel Auth::attempt() 返回 false

Laravel 框架类在 PHPUnit 数据提供程序中不可用

未定义的类常量App\Providers\RouteServiceProvider::HOME

如何卸载 Laravel?

SQLSTATE [01000]:警告:1265 列的数据被截断(truncated)

Laravel 控制器构造

命令未定义异常

Laravel 检测手机/平板电脑并加载正确的视图

Laravel 5 事件处理程序未触发

Carbon解析到 ISO8601

使用 Carbon 将小时转换为 PM 和 AM

以编程方式而不是从 CLI 运行 Laravel 5 seeder