Run Laravel Jobs in the Right Order with Job Chaining
Imagine importing a CSV file.
You need to:
Upload file
↓
Import products
↓
Generate thumbnails
↓
Update search index
You could dispatch each job separately.
But then you have to manage their order yourself.
Laravel provides Job Chaining for exactly this situation.
Create Your Jobs
For example:
class ImportProducts implements ShouldQueue
{
public function handle(): void
{
// Import products...
}
}
Then:
class GenerateThumbnails implements ShouldQueue
{
public function handle(): void
{
// Generate thumbnails...
}
}
And:
class UpdateSearchIndex implements ShouldQueue
{
public function handle(): void
{
// Update search index...
}
}
Chain Them Together
Use Laravel's Bus::chain():
use Illuminate\Support\Facades\Bus;
Bus::chain([
new ImportProducts,
new GenerateThumbnails,
new UpdateSearchIndex,
])->dispatch();
Laravel runs them in this order:
ImportProducts
↓
GenerateThumbnails
↓
UpdateSearchIndex
The next job isn't dispatched until the previous job successfully completes.
Handle a Failed Chain
You can also define what should happen if one of the jobs fails:
Bus::chain([
new ImportProducts,
new GenerateThumbnails,
new UpdateSearchIndex,
])->catch(function (Throwable $e) {
// Handle failed chain...
})->dispatch();
This is useful when you need to notify an administrator or update the import status.