Home > Enterprise >  Type hinting additional class on a Laravel listener class
Type hinting additional class on a Laravel listener class

Time:07-08

I have my event listener defined as this:

use App\Events\LeadCreated;
use App\Services\LeadService;

class NewLeadNotifyProspectListener
{
    /**
     * Handle the event.
     *
     * @param \App\Events\LeadCreated $event
     * @param App\Services\LeadService $leadService
     * @return void
     */
     public function handle(LeadCreated $event, LeadService $leadService)
    {
        $leadService->notifyProspect($event->lead);
    }
}

And my event

use App\Models\Lead;

class LeadCreated
{
    public Request $request;
    public Lead $lead;

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

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

And I'm calling it in my controller like this:

LeadCreated::dispatch($lead, $request);

The error I'm receiving:

Too few arguments to function App\Listeners\NewLeadNotifyProspectListener::handle(), 1 passed in /vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php on line 424 and exactly 2 expected

I wonder why I'm not able to type-hint LeadService in my listener? What's the proper way to include that class in my listener?

CodePudding user response:

You are loading a dependency, you have to follow Dependency Injection rules. In Laravel you can use Dependency Injection in Controllers like that, because that's build by Laravel/Symfony.

Add your dependency in the constructor instead.

use App\Events\LeadCreated;
use App\Services\LeadService;

class NewLeadNotifyProspectListener
{
    private LeadService $leadService; 

    public function __construct(LeadService $leadService)
    {
        $this->leadService = $leadService;
    }

    /**
     * Handle the event.
     *
     * @param \App\Events\LeadCreated $event
     * @return void
     */
     public function handle(LeadCreated $event)
    {
        $this->leadService->notifyProspect($event->lead);
    }
}

If you have setup the NewLeadNotifyProspectListener correctly, Dependency Injection in Laravel will inject that service in the constructor, just like it would have done in a Controller

  • Related