Home > Back-end >  How can I return multiple queries with Laravel?
How can I return multiple queries with Laravel?

Time:06-27

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 > Pueblo Thrashers </summary>
        <div >
        @foreach($PTh as $PTplayer)
            <p >{{$PTplayer->Name}} {{$PTplayer->LastName}} </p>
        @endforeach
        </div>
     </details>
<details>
 <summary > Raleigh Kings</summary>
    <div >
    @foreach($RKi as $RKplayer)    
    <p >{{$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?

CodePudding user response:

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]);

CodePudding user response:

You can use for it whereIn method value is contained array within the given array

$PT = DB::table('players')->whereIn('Team_ID', $yourIdOfArray)->get();

CodePudding user response:

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 > Team {{ $loop->index }} </summary>
        <div >
            <p >{{$player->Name}} {{$player->LastName}} </p>
        </div>
     </details>
@endforeach
  • Related