問(wèn)題描述
即使在我的 L5 應(yīng)用程序中,我也試圖登錄以設(shè)置上次登錄時(shí)間和 IP 地址.我可以通過(guò)以下方式使其工作:
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 中使用事件處理程序?qū)ο蟮淖罴逊椒ㄊ鞘裁?我嘗試創(chuàng)建一個(gè)事件處理程序并將 auth.login 添加為事件服務(wù)提供程序中的數(shù)組鍵,但是這不起作用.我不確定 auth.login 事件是否可行.如果不是,上面代碼放在哪里最合適.為了測(cè)試,我把它放在了我的 routes.php 文件中,但我知道那不是它應(yīng)該在的地方.
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.*.
有關(guān) 5.2.* 解決方案,請(qǐng)參閱下面的 JuLiAnc 回復(fù).
在處理了兩個(gè)建議的答案并進(jìn)行了更多研究之后,我終于想出了如何按照我最初嘗試的方式做到這一點(diǎn).
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.
我運(yùn)行了以下工匠命令
$ php artisan handler:event AuthLoginEventHandler
然后我更改了生成的類(lèi),刪除了 Event 類(lèi)的導(dǎo)入,并導(dǎo)入了用戶(hù)模型.我還將 User $user
和 $remember
傳遞給 handle 方法,因?yàn)楫?dāng) auth.login 事件被觸發(fā)時(shí),這就是傳遞的內(nèi)容.
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");
}
}
現(xiàn)在我打開(kāi)了 EventServiceProvided.php 并修改了 $listen
數(shù)組如下:
now i opened EventServiceProvided.php and modified the $listen
array as follows:
protected $listen = [
'auth.login' => [
'AppHandlersEventsAuthLoginEventHandler',
],
];
我意識(shí)到如果一開(kāi)始這不起作用,您可能需要
i realized if this doesn't work at first, you may need to
$ php artisan clear-compiled
我們走了!我們現(xiàn)在可以使用事件處理程序類(lèi)通過(guò) auth.login 事件響應(yīng)用戶(hù)登錄!
There we go! we can now respond to the user logging in via the auth.login event using an event handler class!
這篇關(guān)于Laravel 5 中的登錄事件處理的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!