I'm trying to get the job ID inside my jobs. I try $this->job->getJobId()
but it returns an empty string.
<?php
namespace App\Jobs\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Auth;
class SendNotification implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct($notification, $fireShutdown)
{
$this->notification = $notification;
$this->fireShutdown = $fireShutdown;
}
public function handle()
{
dd($this->job->getJobId());
// Some Code
}
}
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.
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.
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
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)"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With