Search code examples
phplaravellaravel-5laravel-5.1

How to inject dependencies to a laravel job


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;
    }
}

Solution

  • 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...
        }
    }