问题
In Laravel 5.2
, i have added my Event Listener (into app\Providers\EventServiceProvider.php
), like:
protected $listen = [
'Illuminate\Auth\Events\Login' => ['App\Listeners\UserLoggedIn'],
];
Then generated it:
php artisan event:generate
Then in the Event Listener file itself app/Listeners/UserLoggedIn.php
, it's like:
<?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!');
}
}
This shows me following Errors:
ErrorException in UserLoggedIn.php line 28:
Argument 2 passed to App\Listeners\UserLoggedIn::handle() must be an instance of App\Listeners\Request, none given
What did i miss, or how can i solve this please?
- Ultimately, i need to write into Laravel Sessions once the User has logged in.
Thank you all.
回答1:
You are trying to initialize App\Listeners\Request;
but it should be Illuminate\Http\Request
. Also this might not work, so for plan B use this code:
public function handle(Login $event)
{
app('request')->session()->put('test', 'hello world!');
}
Dependency Injection Update:
If You want to use dependency injection in events, You should inject classes through constructor like so:
public function __construct(Request $request)
{
$this->request = $request;
}
Then in handle
method You can use local request variable which was stored in constructor:
public function handle(Login $event)
{
$this->request->session()->put('test', 'hello world!');
}
来源:https://stackoverflow.com/questions/36493760/laravel-5-2-how-to-access-request-session-classes-from-own-event-listener