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