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

FallOutBoi's avatar

How can i properly push into a collection?

Hi guys, i am trying to get a massive amounts of records while looping through an array. Right now the way data is collecting is

Collection {#2209 ▼
  #items: array:150 [▼
    0 => Collection {#2405 ▼
      #items: array:150 [▼
        0 => {#2403 …6}
        1 => {#2400 …6}
        2 => {#2397 …6}
        3 => {#2399 …6}
        4 => {#2402 …6}
        5 => {#2398 …6}
        6 => {#2401 …6}
        7 => {#2395 …6}
        8 => {#2394 …6}
        9 => {#2393 …6}
        10 => {#2392 …6}
        11 => {#2391 …6}
        12 => {#2390 …6}
        13 => {#2389 …6}
...

i want the child collection to be emitted so instead of 146 items above it will be 300 and no child collections. This is the way my code is right now.

  $schools = collect();
          foreach($lgas as $lga){
            $school = DB::table('schools')
            ->join('school_categories', 'schools.school_category_id', '=', 'school_categories.id')
            ->leftJoin('school_sub_categories', 'school_sub_categories.id', '=', 'schools.school_sub_category_id')
            ->join('addresses', 'addresses.id', '=', 'schools.address_id')
            ->select('schools.name',
            'schools.code',
            'school_categories.name as category_name',
            'school_sub_categories.name as sub_category_name',
            'schools.email',
            'schools.phone')
            ->where('addresses.lga_id', $lga)
            ->get();
            $schools->push($school);
          }

Is there any possible way that i can achieve that? Thanks in advance

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

push will append an item to a Collection; it happens that your item is itself a Collection. You could use merge instead.

However, I am pretty sure you could achieve this same result with a single database query (and without looping or instantiating a Collection) if you replace ->where('addresses.lga_id', $lga) with ->whereIn('addresses.lga_id', $lgas); but I may be misreading your intentions above.

1 like

Please or to participate in this conversation.