Laravel Job Batching
Laravel's job batching feature allows you to group multiple jobs into a batch and perform actions when the batch completes, fails, or progresses. This is particularly useful for tasks like processing large datasets or executing dependent jobs.
Defining Batchable Jobs
To make a job batchable, include the Illuminate\Bus\Batchable trait in your job class. This provides access to the batch() method, which allows the job to interact with its batch. For example:
Dispatching Job Batches
You can dispatch a batch of jobs using the Bus::batch() method. This method also supports completion callbacks like then, catch, and finally:
Monitoring and Managing Batches
Laravel provides tools to inspect and manage batches:
-
$batch->progress() returns the completion percentage.
-
$batch->cancel() cancels the batch.
-
$batch->failedJobs retrieves the number of failed jobs.
You can also retrieve a batch by its ID using Bus::findBatch($batchId).
Adding Jobs Dynamically
You can add jobs to an existing batch from within a batch job using the add() method:
Batch Failures and Pruning
When a job in a batch fails, the catch callback is triggered. By default, a failed job cancels the entire batch, but you can override this behavior using the allowFailures() method. To clean up old batch records, schedule the queue:prune-batches Artisan command.
Important Considerations
-
Database Migration: Ensure you have a job_batches table by running php artisan make:queue-batches-table and migrating it.
-
Callbacks: Avoid using $this in batch callbacks as they are serialized.
-
Batch Naming: Use the name() method to assign a name for better debugging in tools like Horizon.
Laravel's job batching simplifies handling complex workflows by grouping jobs and providing robust tools for monitoring and managing their execution.