Search code examples
phplaravellaravel-5laravel-5.6laravel-collection

Laravel slice in collection


I've got this code in my Laravel 5.6 controller:

$ads = Advertisement::actives();

$ports = Port::filter($filters)
    ->actives()
    ->paginate(28);

I would like to add every 4th port one advertisement. How could I do this?

So result should be:

//Collection
[
   //Port,
   //Port,
   //Port,
   //Port
   //Advertisement
   //Port
   //Port
   //Port
   //Port
   //Advertisement

   //etc...
]

Solution

  • If each of your add contains the same code, you can do it like this:

    $ports = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
    
    $ads = 'ad';
    
    $ports = $ports->chunk(4)->each->push($ads)->collapse();
    

    This will give you:

    Collection {#530 ▼
      #items: array:14 [▼
        0 => 1
        1 => 2
        2 => 3
        3 => 4
        4 => "ad"
        5 => 5
        6 => 6
        7 => 7
        8 => 8
        9 => "ad"
        10 => 9
        11 => 10
        12 => 11
        13 => "ad"
      ]
    }
    

    But if in $ads you have multiple ads, you need to use a bit longer notation:

    $ports = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
    
    $ads = ['ad1', 'ad2', 'ad3'];
    
    $ports = $ports->chunk(4)->map(function($items, $key) use ($ads) {
        return $items->push($ads[$key]);
    })->collapse();
    
    dd($ports);
    

    This will give you:

    Collection {#530 ▼
      #items: array:14 [▼
        0 => 1
        1 => 2
        2 => 3
        3 => 4
        4 => "ad1"
        5 => 5
        6 => 6
        7 => 7
        8 => 8
        9 => "ad2"
        10 => 9
        11 => 10
        12 => 11
        13 => "ad3"
      ]
    }
    

    For reference you can take a look at Collections documentation