php – How to inject dependencies to a laravel job-ThrowExceptions

Exception or error:

I’m adding a laravel job to my queue from my controller as such

$this->dispatchFromArray(
    'ExportCustomersSearchJob',
    [
        'userId' => $id,
        'clientId' => $clientId
    ]
);

I would like to inject the userRepository as a dependency when implementing the ExportCustomersSearchJob class. Please how can I do that?

I have this but it doesn’t work

class ExportCustomersSearchJob extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels, DispatchesJobs;

    private $userId;

    private $clientId;

    private $userRepository;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userId, $clientId, $userRepository)
    {
        $this->userId = $userId;
        $this->clientId = $clientId;
        $this->userRepository = $userRepository;
    }
}
How to solve:

You inject your dependencies in the handle method:

class ExportCustomersSearchJob extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels, DispatchesJobs;

    private $userId;

    private $clientId;

    public function __construct($userId, $clientId)
    {
        $this->userId = $userId;
        $this->clientId = $clientId;
    }

    public function handle(UserRepository $repository)
    {
        // use $repository here...
    }
}

Answer´╝Ü

In case anyone is wondering how to inject dependency into handle function:

put the following in a service provider

$this->app->bindMethod(ExportCustomersSearchJob::class.'@handle', function ($job, $app) {
    return $job->handle($app->make(UserRepository::class));
});

laravel documentation for job

Leave a Reply

Your email address will not be published. Required fields are marked *