How to inject dependencies to a laravel job
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
Laravel v5 and after.
Since Laravel v5, dependencies in jobs are handled by themselves. The documentation reads
"You may type-hint any dependencies you need on the handle method and the service container will automatically inject them"
So, now, all you have to do in the handle method of the Job is to add the dependencies you want to use. For example:
use From/where/ever/UserRepository;
class test implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct()
{
//
}
public function handle(UserRepository $userRepository)
{
// $userRepository can be used now.
}
}
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...
}
}