7

In Laravel 5.3, in the controller, we can dispatch a job to the job queue like this:

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

In the Job class which is using InteractsWithQueue trait, in the handle function, we can get the Job ID like this:

$this->job->getJobId();

But, I would like to get the Job ID in my controller after I use the dispatch($job).

How to get the Job ID in controller?

If there is no such function available, can we extend the dispatch helper function to add this function?

userpal
  • 1,483
  • 2
  • 22
  • 38

2 Answers2

11

The dispatch() function will return the Job id:

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

dd($jobId);
baikho
  • 5,203
  • 4
  • 40
  • 47
  • may I know how you search for the API documentation for the `dispatch` function? I tried to search for it in `https://laravel.com/api/5.3/` but could not find it. What is the URL for this function? – userpal Dec 28 '16 at 22:51
  • 1
    `vendor/laravel/framework/src/Illuminate/Foundation/helpers.php` – Fahmi Jan 14 '17 at 10:14
  • @Baik Ho in laravel 5.5 it is protected so can not get the job id is their a way we can get the job id in laravel controller. ? – Muhammad Usama Mashkoor Oct 31 '17 at 08:29
  • 1
    @usama See my answer : https://stackoverflow.com/questions/40329206/how-to-get-the-queued-job-from-job-id-in-laravel/47616524#47616524 – Armin Dec 03 '17 at 08:13
0

Its a quite old question. But maybe who came across this post by google. Laravel is firing an event after a job is queued. Illuminate\Queue\Events\JobQueued

You can add a listener to this event and reach almost all infos incl. The DB id int your event listener.

In your EventServiceProvider attach your listener. In my app it is the JobQueuedListener file

use Illuminate\Queue\Events\JobQueued;

protected $listen = [
        JobQueued::class =>[
            JobQueuedListener::class
        ],

In the JobQueuedListener file you can now access the event var.

public function handle(JobQueued $event)
{
    $this->event  = $event;
    $mainListener = $event->job->class ?? '';
    if ($mainListener == 'App\Listeners\IpBlockedListener') {
        $this->addIdToIpBlockedModel();
    }

    }
Mike Aron
  • 550
  • 5
  • 13