How to change collection to chunks by chunk and chunkWhile method

In this tutorial we will discuss use of laravel collection chunk and chunkWhile method.


Laravel collection chunk

laravel collection chunk() method divide a collection into multiple collections of given size see below example.

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
 
$chunks = $collection->chunk(4);
 
dd($chunks->all());
 
//[[1, 2, 3, 4], [5, 6, 7, 8], [9]]

laravel chunk method mainly use on blade file where you want to show grid data. see below example.

@foreach ($products->chunk(3) as $chunk)
  <div class="row">
    @foreach ($chunk as $product)
      <div class="col-xs-4">{{ $product->name }}</div>
    @endforeach
  </div>
@endforeach

Laravel collection chunkWhile

laravel collection chunkWhile() method change a collection to multiple collection according to condition. according to official doc we take an example.

$collection = collect(str_split('AABBCCCD'));
 
$chunks = $collection->chunkWhile(function (string $value, int $key, Collection $chunk) {
    return $value === $chunk->last();
});
 
$chunks->all();
 
// [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']]
php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links