Laravel 5.2: How to access request and session classes from my own event listener?

In Laravel 5.2 I added my event listener (in app\Providers\EventServiceProvider.php ), for example:

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

Then generated:

 php artisan event:generate 

Then, in the Event Listener file app/Listeners/UserLoggedIn.php it looks like this:

 <?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 the 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 have I missed, or how can I solve this?

  • Ultimately, I need to write in Laravel sessions after the user logs in.

Thanks to everyone.

+3
event-handling session laravel
source share
1 answer

You are trying to initialize App\Listeners\Request; but it should be Illuminate\Http\Request . It may also 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 must enter classes through the constructor as follows:

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

Then in the handle method, you can use the local request variable that was saved in the constructor:

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

All Articles