Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

locopetey's avatar

Guzzle getAsync php laravel pass variable to promise

I am looping through a DB of users to pass data to an API to validate addresses via getAsync. I need to update my DB record based on what the API returns. Problem is that I can't figure out how to pass $user->id to the promise to update the record.

$users = User::all();
$client = new Client();

$promises = (function () use ($users, $client) {
   foreach ($users as $user) {
        yield $client->getAsync('https://some/api/' . $user->address);
    }
})();

$eachPromise = new EachPromise($promises, [
    'concurrency' => 2,
    'fulfilled' => function (Response $response) {
        if ($response->getStatusCode() == 200) {
            //NEED TO ACCESS USER->ID HERE TO UPDATE RECORD IN DB                   
        }
    },
    'rejected' => function ($reason) {
    
    }
]);
$eachPromise->promise()->wait();

Thanks in advance!

0 likes
9 replies
Maria30's avatar
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Exception\RequestException;

$client = new Client();

$promise = $client->requestAsync(
         'GET',
         'http://someapi/1'
);

$promise->then(
        function (Response $resp) {
    echo $resp->getBody();
},
    function (RequestException $e) {
    echo $e->getMessage();
}
);
$promise->wait();

@locopetey This is a very general structure of a requestAsync()

locopetey's avatar

Thanks again for your help. My issues is not with ASYNC But rather how to pass data to the promise from the loop over users. See my example again above..

Looking for this where it is commented out

 //NEED TO ACCESS USER->ID HERE TO UPDATE RECORD IN DB
Maria30's avatar
foreach($users as $user)
{
return $user->id;
}

Or

foreach($users as $user)
{
$userId = $user->id;
}
locopetey's avatar

Thanks again, but it doesn't address the issue. Please read my original post in detail.

learningMonkey's avatar

@locopetey there is a second parameters in the "fulfilled" and "rejected" callbacks - "$index" which is the index of the element that was processed. So you can use the index to look up the item in the users array and then update that particular user.

Please or to participate in this conversation.