How to Get the Job ID in Laravel

If you have worked with the latest versions of Laravel, you must have noticed that when you dispatch a job, it does not return the job ID, as it did in past versions.

But don't worry, there are 2 solutions depending on where you need to get the ID.

Inside the Job

The simplest but not always the most useful way to get the ID is through the getJobId() method inside the job variable of the InteractsWithQueue trait as follows.

<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class MyJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; ... public function handle() { $id = $this->job->getJobId(); } }
Code to Get the ID inside the Job Class

This way you can get the ID inside the job class allowing you to interact with the database through this id.

When the Job is Dispatched

This way to obtain the job id in Laravel is the least known, since it is not shown in the main documentation and you must search within the framework files to discover that the solution is the use of the bus dispatcher of Laravel, as shown in the following code.

<?php namespace App\Services; use App\Jobs\MyJob; use Illuminate\Contracts\Bus\Dispatcher; class MyService { ... public function my_method() { $id = app(Dispatcher::class)->dispatch(new MyJob()); } }
Code to Get the ID Through the Dispatcher

As you can see, this is not a solution that you would find directly but it becomes logical when we know how the framework is composed.