Laravel - Send an asynchronous request with Guzzle

Hamid Rohani
2 min readFeb 16, 2022

--

Today the Async requests are very important and all of the great programming languages try to give this possibility to their developers.

You maybe want to send a request and actually, you don’t want to wait for the response of that request, So the async requests could help you in those situations.

First of all, we need to create a handler and a client object

use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlMultiHandler;

$handler = new CurlMultiHandler();
$client = new Client(['handler' => $handler]);

After that, we want to call a post request on the same page

$client->postAsync($this->url, [    'headers' => [
// header will be here
],
'json' => [
// body will be here
]
])->then(function ($result) {
// request returned successfully with results
})
->otherwise(function ($reason){
// The request was not complete and there are some reasons
});

There are two kinds of callback methods after the postAsync that the then one gets a function and give the result into the function.

So if the request is successful, your code in the method then will be executed.

And also if there were any errors your code into the otherwise will be executed.

For executing the async request you have to call the handler that was created before and call the method named tick.

$handler->tick();

Notice: The guzzle is not just for the Laravel and you can use it everywhere inside PHP.

This is all of them:

use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlMultiHandler;
$handler = new CurlMultiHandler();
$client = new Client(['handler' => $handler]);
$client->postAsync($this->url, ['headers' => [
// header will be here
],
'json' => [
// body will be here
]
])->then(function ($result) {
// request returned successfully with results
})
->otherwise(function ($reason){
// The request was not complete and there are some reasons
});
$handler->tick();

Just like that

Hamid Roohani

--

--