Articles Snippets Projects

Dispatch Jobs in Laravel Tinker

Why Laravel Tinker does not dispatch Jobs?

August 8th ʼ22 1 week ago

3 min 449 words

This article is co-written by me (Yunus Emre Deligöz) and Turan Karatuğ, also available in Turkish, co-published on my blog and Medium.

TL;DR

Just add ;1 suffix after the dispatch command:

SendEmailJob::dispatch();1;

Dispatching Jobs through Laravel Tinker

If you want to dispatch a job into the queue through Laravel Artisan Tinker, you’ll open the Tinker and write:

SendEmailJob::dispatch();

And see the job is actually is not dispatched. If you run the command again, you’ll see the same response but the job is dispatched into the queue only once.

Why Laravel Tinker did not Dispatch the Job for the First Time?

The problem is that Laravel Tinker keeps the generated PendingDispatch objects in memory for the user to use in subsequent commands. When this object is destroyed, it actually dispatches the job.

There was a discussion about this on Laravel Tinker GitHub Repo.

Solution

To solve this job in the very right way, you can dispatch the job through Laravel’s Dispatcher class:

app(\Illuminate\Contracts\Bus\Dispatcher::class)
  ->dispatch(new SendEmailJob());

To solve this quickly and hacky:

SendEmailJob::dispatch();1

By adding a ;1 suffix, Tinker will not keep PendingDispatch objects in memory and dispatches jobs.