2

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.

0

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works...i just had to edit this line ...->get('https://{baseUrl}/v3/virtual-cards/$card' to ...->get('https://{baseUrl}/v3/virtual-cards/'.$card.''
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.