gpt4 book ai didi

拉拉维尔 5.2 : How to access Request & Session Classes from own Event Listener?

转载 作者:行者123 更新时间:2023-12-02 21:22:03 26 4
gpt4 key购买 nike

Laravel 5.2 中,我添加了事件监听器(到 app\Providers\EventServiceProvider.php 中),例如:

protected $listen = [
'Illuminate\Auth\Events\Login' => ['App\Listeners\UserLoggedIn'],
];

然后生成它:

php artisan event:generate

然后在事件监听器文件本身 app/Listeners/UserLoggedIn.php 中,如下所示:

<?php

namespace App\Listeners;

use App\Listeners\Request;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Auth\Events\Login;

class UserLoggedIn
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{

}

/**
* Handle the event.
*
* @param Login $event
* @return void
*/
public function handle(Login $event, Request $request)
{
$request->session()->put('test', 'hello world!');
}
}

这显示了以下错误:

ErrorException in UserLoggedIn.php line 28:
Argument 2 passed to App\Listeners\UserLoggedIn::handle() must be an instance of App\Listeners\Request, none given

我错过了什么,或者我该如何解决这个问题?

  • 最终,我需要在用户登录后写入 Laravel session 。

谢谢大家。

最佳答案

您正在尝试初始化App\Listeners\Request;,但它应该是Illuminate\Http\Request。另外,这可能不起作用,因此对于 B 计划,请使用以下代码:

public function handle(Login $event)
{
app('request')->session()->put('test', 'hello world!');
}
<小时/>

依赖注入(inject)更新:

如果你想在事件中使用依赖注入(inject),你应该通过构造函数注入(inject)类,如下所示:

public function __construct(Request $request)
{
$this->request = $request;
}

然后在handle方法中您可以使用存储在构造函数中的本地请求变量:

public function handle(Login $event)
{
$this->request->session()->put('test', 'hello world!');
}

关于拉拉维尔 5.2 : How to access Request & Session Classes from own Event Listener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36493760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com