Do you know that Laravel provides asynchronous HTTP client requests and uses the async() method, you can make your HTTP call asynchronous HTTP client requests? In this tutorial, I will discuss a complete example of asynchronous HTTP client requests in the Laravel 10 application.

To show you Laravel async request example, I will use get request and also show you how to send multiple async requests at the same time in Laravel using an HTTP client.

So let's see the example of Laravel asynchronous request.

laravel-10-async-http-request

If we want to create an asynchronous request, we can create it like so.

<?php

$promise = Http::async()->get('https://www.laravelia.com');

 

You can get the result from async http request like:

<?php

use Illuminate\Support\Facades\Http;

$promise = Http::async()->get('https://www.laravelia.com')->then(function ($response) {
    return $response->body();
});

 

If we want to make multiple async requests at the same time, we can use the pool like so. Laravel provides a pool and we can use it like the below to create multiple async requests:

<?php

use Illuminate\Http\Client\Pool;

// the waiting time will be ~6 seconds instead of 12
$responses = Http::pool(fn (Pool $pool) => [
    $pool->get('https://httpbin.org/delay/6')->then(/* ... */),
    $pool->get('https://httpbin.org/delay/3')->then(/* ... */),
    $pool->get('https://httpbin.org/delay/3')->then(/* ... */),
]);

$responses[0]->ok();
$responses[1]->successful();

 

Read also: How To Revoke Token In Laravel Passport?

 

Conclusion

Now we know laravel async request. Hope this laravel asynchronous request example tutorial will help you to handle laravel async http request.

Category : #laravel

Tags : #laravel , #laravel api