Laravel 5.2 : How to access Request & Session Classes from own Event Listener?

感情迁移 提交于 2020-01-23 11:37:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!