Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type hinting additional class on a Laravel listener class

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading