Dispatch Laravel Jobs Via Artisan


July 13th, 2021


Laravel Artisan Dispatchable is a package by Spatie to register queue jobs as Artisan commands. The Laravel scheduler can schedule queue jobs that do not block the scheduler, but this approach has one downside:

You have to choose between using an artisan command + blocking the scheduler on the one hand, and job + not blocking the scheduler on the other hand.

Using our package, you don't have to make that choice anymore. When letting your job implement Spatie's ArtisanDispatchable, you will not block the scheduler and can still execute the logic via Artisan.

The way this package works is that you implement this packages ArtisanDispatchable interface, and your job is available as an artisan command:

1use Illuminate\Contracts\Queue\ShouldQueue;
2use Spatie\ArtisanDispatchable\Jobs\ArtisanDispatchable;
4class ProcessPodcast implements ShouldQueue, ArtisanDispatchable
6 public function handle()
7 {
8 // perform some work...
9 }

The neat part about this package is that it comes with conventions that allow your job to be available to artisan without any more work, using the kebab-case of the class name:

1# Execute via Artisan
2php artisan process-podcast
4# Put your job on the queue instead of executing immediately
5php artisan process-podcast --queued
7# Eloquent models as constructor arguments
8# Podcast model instance as a constructor argument
9php artisan process-podcast --podcast="1234"

While this package has conventions of command names, the package allows you to override both the command name and description.

You can learn more about this package, get full installation instructions, and view the source code on GitHub. Also, check out the announcement post by Freek Van der Herten.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.