9

Until Laravel 5.4, the dispatch() method returned the queue job id.

$job = (new JobClass())->onQueue('queuename');
$jobId = dispatch($job);

dd($jobId); // prints the job id

In 5.5, it returns a PendingDispatch object, which does not seem to have a method to retrieve the job id.

I've already tried with dispatch_now(), but it executes the job immediately and synchronously, while I want it to be executed in the background.

SteveVg
  • 481
  • 5
  • 11

3 Answers3

18

After opening an issue at Laravel github, the solution was to use:

app(\Illuminate\Contracts\Bus\Dispatcher::class)->dispatch($job)

instead of

dispatch($job)
SteveVg
  • 481
  • 5
  • 11
6

You might also consider using DispatchesJobs trait:

class MyClassName()
{
    use DispatchesJobs;

    ....

    $job = (new JobClass())->onQueue('queuename');

    $jobId = $this->dispatch($job);
alexeydemin
  • 2,672
  • 3
  • 27
  • 26
  • 1
    This worked for me in Laravel 7. Very happy to have found a working solution. Note that I had to add this line near the top of the file: use Illuminate\Foundation\Bus\DispatchesJobs; – Derrick Miller Aug 14 '20 at 14:55
-1

alexeydemin Code works as intended.

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Eyad Mohammed Osama Apr 04 '23 at 11:46