問題描述
即使在我的 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 中的登錄事件處理的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!