BLOG // May 25, 2021

Send HTTP requests in parallel with Laravel

A great performance tip for Laravel is the ability to send HTTP requests concurrently. This is especially useful when you are doing things like sending multiple webhooks and similar examples.

use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;

[...]

$responses = Http::pool(fn (Pool $pool) => [
    $pool->get('http://localhost/first'),
    $pool->get('http://localhost/second'),
    $pool->get('http://localhost/third'),
]);

return $responses[0]->ok() &&
       $responses[1]->ok() &&
       $responses[2]->ok();

As you can see in the above example, the three URLs are requests in parallel and each return an array value in $responses.

You can name the responses in the array as well:

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

return $responses['first']->ok();

Comments

Subscribe to new articles

If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.