Laravel Jobs Batching
Laravel Jobs Batching

Laravel Jobs Batching

Laravel 8 has unveiled a much-anticipated feature known as Laravel Jobs Batching, enabling the simultaneous execution of multiple tasks and flexible progress monitoring, even in the presence of errors.

To commence, execute the following commands to create the job_batches table for storing information about job batches:

php artisan queue:batches-table
php artisan migrate

Finding Batch by ID

To retrieve batch information based on its ID, utilize the Bus facade with the findBatch method:

$batch = Bus::findBatch("909db655-ed38-4739-89ea-ca6c1b13a5a0");

Callbacks

Bus::batch() provides several functionalities in the form of callbacks:

  • then: Executed when all jobs are successful.
  • catch: Executed when errors occur during the execution of any job in the batch.
  • finally: Executed when all jobs conclude processing, regardless of success or failure.
$batch = Bus::batch([
    new ImportExcel(1, 100),
    new ImportExcel(101, 200),
    new ImportExcel(201, 300),
    new ImportExcel(301, 400),
    new ImportExcel(401, 500),
])->progress(function (Batch $batch) {
    // A single job has completed successfully...
})->then(function (Batch $batch) {
    // All jobs completed successfully...
})->catch(function (Batch $batch, Throwable $e) {
    // First batch job failure detected...
})->finally(function (Batch $batch) {
    // The batch has finished executing...
})->dispatch();

Batch Object

The Batch Object comprises useful properties providing information about the batch and the status of its jobs.

{
    "id": "941eaf3c-7e03-4861-92b9-49713402b9e4",
    "name": "",
    "total_jobs": 0,
    "pending_jobs": 0,
    "failed_jobs": 0,
    "failed_job_ids": "[]",
    "options": "a:0:{}",
    "cancelled_at": null,
    "created_at": 1628595099,
    "finished_at": null
}

Now, having grasped the feature, let's delve into an example to solidify understanding of job batches.

Creating a User Addition Job

Firstly, we need a job to add mock data to the users' table. Run the following command to the job:

php artisan make:job CreateUserJob

Next, open the CreateUserJob.php file in the app/Jobs directory and modify it as follows:

// CreateUserJob.php

namespace App\Jobs;

use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class CreateUserJob implements ShouldQueue
{
    use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct()
    {
        //
    }

    public function handle()
    {
        \App\Models\User::factory(10)->create();
    }
}

Note: When utilizing job batches, include the following facade; it is not automatically added when creating a job:

use Illuminate\Bus\Batchable;

Verifying Laravel Job Batches Activity

In this step, we need to add a controller to execute the job.

To achieve this, run the following command:

php artisan make:controller TestQueueJobController

Now, open TestQueueJobController.php and update it:

// TestQueueJobController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Jobs\CreateUserJob;
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
use Throwable;

class TestQueueJobController extends Controller
{
    public function run()
    {
        $batch = Bus::batch([
            new CreateUserJob(),
            new CreateUserJob()
        ])->dispatch();
    }
}

Then, open routes/web.php and add the following line:

Route::get('job-batches', [App\Http\Controllers\TestQueueJobController::class,'run']);

Now, access the /job-batches URL in your browser to execute the user creation job.

After a job is processed, handle the queue with the following command:

php artisan queue:work

Upon completion, you'll have 20 new users added to the users table.

In conclusion, we've successfully demonstrated a simple example of Laravel Queue. I hope this guide proves helpful for your tasks. If you have any questions, feel free to contact us through the provided contact page. Thank you.