Make an api call using foreach to loop over an array

Viewed 724

I have this code below that gets all of a user's cardId which I need to make an api call to get details of each card.The cardIds are saved when a card is created. The endpoint to get a card is this- https://{baseUrl}/v3/virtual-cards/id where i need to pass the user's cardId as id. In my application I am making it possible for a user to create multiple cards so on creation of a card I collect the cardId and save it to my database. I can get all the cardIds from the database using

$auth_user = Auth::user()->id;
$card = Card::where('user_id', $auth_user)->pluck('card_id');

Now I want to loop over all the cardIds in the database to make the api call getting all the datails for each cardId. What i have tried.

 public function getCard(Request $request){
        $auth_user = Auth::user()->id;
        $card = Card::where('user_id', $auth_user)->pluck('card_id');
         foreach ($card as $userCard) {
        $response = Http::withToken('{SEC_KEY}')->get('https://{baseUrl}/v3/virtual-cards/$userCard', [
          ]);
          return $response->json();
         }
  
    }

But the foreach does not seem to work.

2 Answers

Note Actually this mystery is resolved by baikho and you should accept his answer as he was first, pitty that didn't give any sample.

You shouldn't return value in the first iteration, instead, collect them i.e. in array first and return whole set, also names of variables are confusing.

public function getCardResponses(Request $request): array
{
    $auth_user = Auth::user()->id;
    $cards = Card::where('user_id', $auth_user)->pluck('card_id');
    $responses = [];
    foreach ($cards as $card) {
        $response = Http::withToken('{SEC_KEY}')->get('https://{baseUrl}/v3/virtual-cards/$userCard', [
        ]);
        $responses[] = $response->json();
    }
    return $responses;
}

The foreach() doesn't work because you are one-off returning a value in the first iteration. Either that is expected behaviour or you may want to gather values in an array and return the value outside of the loop.

Related