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

dgoetz's avatar

How to return multiple db results with same query in a foreach loop?

Hello there, I think it's best to explain what I am trying to accomplish in order to explain my question. I am trying to create gamelogs for each player that has been selected to be a part of a particular game. The code to gather selected players and attempt to create a gamelog as of now looks like this:

$list = request(['player_ids']);

        foreach ($list as $player_id) {

            $players[] = Player::where('id', $player_id)->get();
            
            foreach($players as $player) {
            
            $gamelogs = Gamelog::create(request(['player_id', 'game_id', 'goals', 'assists', 'yellows', 'red']));
            
            }
        }

The issue comes when I try run the foreach loop in which I'm trying to iterate through each player_id and retrieve all of said players from the database. When I dd($players) I only get the first player selected from the checkbox form I have set up instead of an array of players, but when I dd($player_id) I get the complete list of player ids.

How would I accomplish this? And then I'm guessing I will have a similar issue with inserting gamelogs within a foreach loop, so how would that be accomplished? Is there an different/more effective way to do this?

0 likes
2 replies
xantios's avatar
$list = request(['player_ids']);
$players = Playere::whereIn('id',$list);

dd($players);

the whereIn method uses an array of id's to pull all users from the database. it also saves you a loop :)

dgoetz's avatar

@xantios but then how would I pull those id's from that array to insert into each of the individual gamelogs?

Please or to participate in this conversation.