Chunk data in Laravel

Here is a tip if you work with Laravel framework. There is a handy function to "chunk" your database query results into smaller groups of data. Very useful when doing grids in html/css or whenever you need to break up a pile of data in to smaller chunks.

Jul 5, 2016

Examples

Controller:

$items = Item::all(); // Fetch some data

View:

@foreach($items->chunk(3) as $row)
    <div class="grid__row">
        @foreach($row as $item)
            <div class="grid__item">
                {{ $item->title }}
            </div>
        @endforeach
    </div>
@endforeach

It works on all collections, not just database queries. Another example with static data:

$colors = collect(['orange', 'blue', 'green', 'red', 'yellow', 'purple']);
$chunks = $colors->chunk(3);

print_r($chunks);

/*
Output:

Array
(
    [0] => Array
        (
            [0] => orange
            [1] => blue
            [2] => green
        )

    [1] => Array
        (
            [3] => red
            [4] => yellow
            [5] => purple
        )

)
*/

Read more about chunk in the official docs.