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

ncltours's avatar

Query nested 2 layers deep collections in laravel

I have the following nested collection:

Collection {#1195
  #items: array:2 [
    "ip_address" => "192.168.1.89"
    "supplier" => "HitchHiker"
    "flights" => array:2 [
      0 => Collection {#1196
        #items: array:1 [
          "id" => "3559ee11-fc99-4b43-a86f-67f0e3257f4c"
        ]
    ]    
  ]

I want to query with respect to "id", Its the 2nd level nested collection.

I want to use "where" clause to query the collection with respect to "id". How can I do it.

     data = $data->whre(''id", $id)

I can only do on the first level collection. How to do in the second level nested collection?

0 likes
15 replies
Sinnbeck's avatar

Can you try formatting your code with ``` on the line before and after. Also please show the code you have so far for the query

ncltours's avatar

Hi I did format. Can you help me solve this?

Sinnbeck's avatar

Hmm it seems it is three levels deep. Can you show how you create this collection?

ncltours's avatar

HI it gives error as {message: "Call to a member function where() on array",…}

ncltours's avatar
    {

 
      $solutionSet[] = array(
        'ip_address'       => $ip_address
       );
   
    foreach($fareresponse->flight->legs->fareresponseleg->connections->fareresponseconnection as $connection)
      {

        $availstring   = (string)$connection->availstring;

        $outboundFlights[]    = array(
          "id"                   => $id,
          'availstring'          => $availstring
                
        );

      foreach($connection->segments->fareresponsesegment as $fareresponsesegment)
        {
        
          $outboundairsegments[] = array(
             "id"                 => $id,
             "availstring"        => $availstring,
             "flightType"         => "outbound"
           

          );
        }
      }
      
    }

     $outbound  = array();
        $outboundFlights = $outboundFlights->map(function($item) use ($outboundairsegments){
        foreach($outboundairsegments as $outboundairsegment)
        {
          if(preg_replace('/[^A-Za-z0-9\-]/', '',$outboundairsegment['availstring']) == preg_replace('/[^A-Za-z0-9\-]/', '',$item['availstring']))
          {
            $outbound[]   = $outboundairsegment;   
            }
           }
          return collect($item)->put('outboundairsegments', $outbound);     
        });


       $data  = array();
        $solutionSet = $solutionSet->map(function($item) use ($outboundFlights){
        foreach($outboundFlights as $outboundFlight)
        {
          if(preg_replace('/[^A-Za-z0-9\-]/', '',$outboundFlight['id']) == preg_replace('/[^A-Za-z0-9\-]/', '',$item['id']))
          {
            $data[]   = $outboundFlight;   
            }
           }
          return collect($item)->put('outboundFlights', $data);     
        }); 
             
    $price = array();
     $solutionSet = $solutionSet->map(function($item) use ($priceDetails){
      foreach($priceDetails as $priceDetail)
      {
        if(preg_replace('/[^A-Za-z0-9\-]/', '',$priceDetail['id'])  == preg_replace('/[^A-Za-z0-9\-]/', '',$item['id']))
        {
          $price[]  = $priceDetail;
          }
        }
        return collect($item)->put('priceDetails', $price);
     });

  } ```
Sinnbeck's avatar

Sorry but that code is almost unreadable unless I can actually debug it. I don't see you set flights anywhere in that code? Work on getting flights to point to a collection, not a an array with a collection inside

Edit :seems my first response was overwritten somehow.

ncltours's avatar

sorry "flights" = "outboundFlights",

$solutionSet = $solutionSet->map(function($item) use ($numOfStops) {
                $item   = collect($item['outboundFlights'])->whereIn('outNumStops', $numOfStops);
                return $item;
            });

If i put collect(), then it works, there is no error on where() on array

Sinnbeck's avatar

Yes it would, but is the result correct?

ncltours's avatar

No, There is an issue of not filtering properly.

Sinnbeck's avatar

As expected. Like I said, it is three levels deep not two :)

Collection > array > collection

ncltours's avatar

Yeah. Thats true. Is creating collection into 3 level depth fine? Is it the good practise?

Sinnbeck's avatar

Try changing this line (remove [])

$data   = $outboundFlight;

And then you can filter like this if I understand you correctly

$data = $data->filter(function($item) use ($id) {
    return !! $item->outboundFlight->firstWhere('id', $id);
});
ncltours's avatar

Hi thanks, I am sorry I didn't get you.

The Below code works

$solutionSet = $solutionSet->map(function($item) use ($numOfStops) {
                $item['outboundFlights']   = collect($item['outboundFlights'])->whereIn('outNumStops', $numOfStops);
                return $item;
            });

It filters fine, But how can i come out to root(1st level collection) and display the sorted collections as a whole.

ncltours's avatar

Hi I tried the above one which you have given, But it gives error.

Sinnbeck's avatar

Well without knowing the error I have a hard time giving advise

Please or to participate in this conversation.