Laravel 5.8 How to get the job Id?

Just found this answer and it seems to be still compatible on 5.8!

Routes file

Route::get('/queue/{count?}', function($count = 10) {
    $source = new stdClass;
    $source->count = $count;

    // dump(TestQueue::dispatch($source)->delay(now()->addSeconds(10)));
    dump(app(\Illuminate\Contracts\Bus\Dispatcher::class)->dispatch(new TestQueue($source)));

    return "Queued! Will loop {$source->count} times.";
});

TestQueue class file

class TestQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $source;

    public function __construct(\stdClass $source)
    {
        $this->source = $source;
    }

    public function handle()
    {
        for ($i = 1; $i <= $this->source->count; $i++) {
            logger("Loop #{$i} of {$this->source->count}");
            sleep(1);
        }
    }
}

In browser

Real database ID column!


WARNING: It looks can't implement delays. It just fires out whenever you call it.

    dump(
        app(\Illuminate\Contracts\Bus\Dispatcher::class)
            ->dispatch(new TestQueue($source))
            ->delay(now()->addSeconds(10))
    );

ERROR: Call to a member function delay() on integer {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function delay() on integer at ...web.php:50)"}


The following will allow you to get the job id. Try to copy the code below and dispatch it with a simple route.

class TestJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        echo $this->job->getJobId();
    }
}

And the following route to test it.

Route::get('/trigger', function () {
    dd(dispatch(new \App\Jobs\TestJob()));
});

In your terminal, you should now see the following, with the id of your given job.

Terminal returning the job id

If your queue listener isn't running you can start it by typing the following in the terminal

php artisan queue:work redis --tries=3

If you are trying to return the id to your controller/route, you cannot do this with an async/queued job due to the nature of it being async/queued.