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();
@locopetey download insomnia https://insomnia.rest/
it's a very good tool to inspect your API, and it also generates code in PHP!
I will try later to share a simple example.
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
@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.