Http Client Batch Method in Laravel 12.32

Last updated on by

Http Client Batch Method in Laravel 12.32 image

Never Miss a Laravel Release 🚀

Sign up and get an email with each new Laravel release

The Laravel team released version 12.32.0 this week with a new HTTP batch method, an "after" rate limiting method to control rate limiting by response, batch job failure callback support, and more.

HTTP Batch Requests

Wendell Adriel contributed an Http::batch() method to give you a way of working with concurrent requests in a batch, and allows you to define various callbacks for the batch's lifecycle:

use Illuminate\Http\Client\Batch;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
 
$responses = Http::batch(fn (Batch $batch) => [
$batch->get('http://localhost/first'),
$batch->get('http://localhost/second'),
$batch->get('http://localhost/third'),
])->before(function (Batch $batch) {
// The batch has been created but no requests have been initialized...
})->progress(function (Batch $batch, int|string $key, Response $response) {
// An individual request has completed successfully...
})->then(function (Batch $batch, array $results) {
// All requests completed successfully...
})->catch(function (Batch $batch, int|string $key, Response|RequestException $response) {
// First batch request failure detected...
})->finally(function (Batch $batch, array $results) {
// The batch has finished executing...
})->send();

You can also name your requests using the as() method as follows:

$responses = Http::batch(fn (Batch $batch) => [
$batch->as('first')->get('http://localhost/first'),
$batch->as('second')->get('http://localhost/second'),
$batch->as('third')->get('http://localhost/third'),
])->send();

Finally, the Http batch has various properties and methods you can use to inspect the batch:

// The number of requests assigned to the batch...
$batch->totalRequests;
 
// The number of requests that have not been processed yet...
$batch->pendingRequests;
 
// The number of requests that have failed...
$batch->failedRequests;
 
// The number of requests that have been processed thus far...
$batch->processedRequests();
 
$batch->finished(); // Bool
$batch->hasFailures(); // Bool

You can see the implementation in Pull Request #56946. The request batching documentation provides usage details.

Database afterRollback() Callback Support

Malte Kuhr contributed an afterRollback() method to respond to database transactions that are rolled back:

use Illuminate\Support\Facades\DB;
 
DB::transaction(function () {
DB::afterCommit(function () {
// ...
});
 
DB::afterRollBack(function () {
// ...
});
 
// Run code in the transaction...
// If the transaction fails, the `afterRollback()` callback will run.
});

Batch Job Failure Callback Support

Yitz Willroth updated PendingBatch::allowFailures() to allow callbacks or an array of callbacks. Before this PR, allowFailures() was a way to indicate that batches could disable the default behavior of being cancelled when a failure happens. If you pass a callback (new behavior), it will run on each failure:

// New usage example:
$batch->allowFailures(function ($batch, $exception) {
// Handle individual job failure
Log::error("Job failed in batch {$batch->id}: {$exception->getMessage()}");
});

See Pull Request #55916 for implementation details and discussion.

Introduce "after" Rate Limiting

Tim MacDonald contributed an after() method you can use to rate limit based on the response. He had this to say about it in the pull request:

Currently, it is only possible to rate limit based on the request. Often, it can be useful to rate limit based on the response.

From the original PR: For example, imagine you have a sign up endpoint that could return validation errors. If you want to throttle to a single sign up per day for an IP address, any validation response would trigger the rate limiter making it impossible to sign up again for the day.

Another example is rate limiting 404 responses to mitigate enumeration attacks on resource identifiers. If a single user hits a certain level of 404 responses in a short time frame, they could be attempting enumeration attacks.

Here's the example from the same pull request description of how this callback might be used:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Symfony\Component\HttpFoundation\Response;
 
/*
* Ensure a user can only hit ten 404 responses in a minute before they are
* rate limited to ensure users cannot enumerate resource IDs.
*/
RateLimiter::for('resource-not-found', function (Request $request) {
return Limit::perMinute(10)
->by("user:{$request->user()->id}")
 
// The new `after` hook...
 
->after(function (Response $response) {
return $response->getStatusCode() === 404;
});
});

Release notes

You can see the complete list of new features and updates below and the diff between 12.31.0 and 12.32.0 on GitHub. The following release notes are directly from the changelog:

v12.32.0

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm

The latest

View all →
Vocalizer: Local Text-to-Speech for PHP image

Vocalizer: Local Text-to-Speech for PHP

Read article
Build a Laravel Scout Search Endpoint With the HTTP QUERY Method image

Build a Laravel Scout Search Endpoint With the HTTP QUERY Method

Read article
Enforce Per-Action Waiting Periods in Laravel with Cooldown image

Enforce Per-Action Waiting Periods in Laravel with Cooldown

Read article
First-Party Image Processing in Laravel 13.20 image

First-Party Image Processing in Laravel 13.20

Read article
Laravel Legacy Bridge: Carry Authenticated Sessions from a Legacy App into Laravel image

Laravel Legacy Bridge: Carry Authenticated Sessions from a Legacy App into Laravel

Read article
Laravel Quota: Usage Budgets for Calendar Periods image

Laravel Quota: Usage Budgets for Calendar Periods

Read article