我想重構一些事件,以便創建事件訂戶類。如何將模型事件添加到Laravel 5.1中的事件訂戶類中
class UserEventListener
{
public function onUserLogin($event, $remember) {
$event->user->last_login_at = Carbon::now();
$event->user->save();
}
public function onUserCreating($event) {
$event->user->token = str_random(30);
}
public function subscribe($events)
{
$events->listen(
'auth.login',
'App\Listeners\[email protected]'
);
$events->listen(
'user.creating',
'App\Listeners\[email protected]'
);
}
}
我註冊監聽如下:
protected $subscribe = [
'App\Listeners\UserEventListener',
];
添加以下到用戶模式的引導方法如下:
public static function boot()
{
parent::boot();
static::creating(function ($user) {
Event::fire('user.creating', $user);
});
}
但是當我嘗試登錄我得到以下錯誤:
Indirect modification of overloaded property App\User::$user has no effect
onUserLogin
簽名有什麼問題?我以爲你可以使用$ event-> user來訪問用戶...
這是一個關於laravel 5.1的問題。我認爲模型觀察者更多地使用laravel 5. – adam78
它們仍然存在於5.1中,並且尚未被棄用。但正如我所說,這只是其中一種選擇,如果您願意,可以隨意使用活動用戶。 –