How can I return multiple queries with Laravel?

Viewed 64

I am making a random website(own project for uni) that stores info about recent sports games and teams(team names and player names are made up) and I'd like to find out how can I(or what is the best way) to return player names that belong to their team. Code example from .blade

    <details>
         <summary class="displayTeams"> Pueblo Thrashers </summary>
        <div class="allplayers">
        @foreach($PTh as $PTplayer)
            <p class="displayTeamsPlayer">{{$PTplayer->Name}} {{$PTplayer->LastName}} </p>
        @endforeach
        </div>
     </details>
<details>
 <summary class="displayTeams"> Raleigh Kings</summary>
    <div class="allplayers">
    @foreach($RKi as $RKplayer)    
    <p class="displayTeamsPlayer">{{$RKplayer->Name}} 
   {{$RKplayer>LastName}}</p>
    @endforeach  
    </div>
 </details>

Code example from my controller:

function showPlayers(){
    $PT = DB::table('players')->where('Team_ID', '1')->get();
    $RK = DB::table('players')->where('Team_ID', '2')->get();
return view('WHL', ['PTh' => $PT], ['RKi' => $RK]);

I have 6 more teams that I need to get players from, what's the best possible way to do that?

2 Answers

You can user orWhere() in your Querie, like that :

 $PT = DB::table('players')->where('Team_ID', '1')->orWhere('Team_ID', '1')->orWhere('Team_ID', '3')->get(); return view('WHL', ['PTh' => $PT]);

You could use ->whereIn() like this:

function showPlayers(){
    $teams = [1, 2, 3, 4, 5, 6];
    $players = DB::table('players')->whereIn('Team_ID', $teams)->get();
    
   return view('WHL', ['players' => $players]);
}

And then in the blade file you can do the following

@foreach($players as $player)
    <details>
         <summary class="displayTeams"> Team {{ $loop->index }} </summary>
        <div class="allplayers">
            <p class="displayTeamsPlayer">{{$player->Name}} {{$player->LastName}} </p>
        </div>
     </details>
@endforeach
Related