Laravel chunkBy(): Group Adjacent Collection Items | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com) [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles  ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

  [ home ](https://msaied.com)    [ articles ](https://msaied.com/articles)    Group Adjacent Collection Items in Laravel with chunkBy()        On this page       1. [  What Is chunkBy() in Laravel? ](#what-is-codechunkbycode-in-laravel)
2. [  chunkBy() vs. groupBy(): Adjacent, Not Global ](#codechunkbycode-vs-codegroupbycode-adjacent-not-global)
3. [  Streaming Large Datasets with LazyCollection ](#streaming-large-datasets-with-codelazycollectioncode)
4. [  Two Gotchas Worth Knowing ](#two-gotchas-worth-knowing)
5. [  Key Takeaways ](#key-takeaways)

  ![Group Adjacent Collection Items in Laravel with chunkBy()](https://cdn.msaied.com/626/8cc4b384a3f740d25d1f8ff8520d36a0.png)

 [  Laravel ](https://msaied.com/articles?category=laravel) [  Tips &amp; Tricks ](https://msaied.com/articles?category=tips-tricks)  #Laravel   #Collections   #LazyCollection   #Laravel 13   #Performance  

 Group Adjacent Collection Items in Laravel with chunkBy() 
===========================================================

     3 Sep 2026      3 min read    ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said  

       Table of contents

1. [  01   What Is chunkBy() in Laravel?  ](#what-is-codechunkbycode-in-laravel)
2. [  02   chunkBy() vs. groupBy(): Adjacent, Not Global  ](#codechunkbycode-vs-codegroupbycode-adjacent-not-global)
3. [  03   Streaming Large Datasets with LazyCollection  ](#streaming-large-datasets-with-codelazycollectioncode)
4. [  04   Two Gotchas Worth Knowing  ](#two-gotchas-worth-knowing)
5. [  05   Key Takeaways  ](#key-takeaways)

 What Is `chunkBy()` in Laravel?
-------------------------------

Laravel 13.30 ships `chunkBy()`, a concise shorthand for the most common `chunkWhile()` pattern. Instead of writing:

```php
$products->chunkWhile(
    fn ($value, $key, $chunk) => $value->parent == $chunk->last()->parent
);

```

You can now write:

```php
$products->chunkBy('parent');

```

The method accepts either a dot-notation key string or a callback:

```php
$lineItems->chunkBy('order_id');
$lineItems->chunkBy(fn ($item) => $item->order_id);

// Dot notation reaches into nested objects
$users->chunkBy('address.city');

```

The key is resolved via `data_get()`, so nested array and object access works out of the box.

`chunkBy()` vs. `groupBy()`: Adjacent, Not Global
-------------------------------------------------

This is the most important distinction to internalize. `chunkBy()` only groups **consecutive** items that share the same value — it does not collect all matching items across the entire collection:

```php
collect([1, 1, 2, 2, 1, 1])->chunkBy(fn ($v) => $v);
// [[1, 1], [2, 2], [1, 1]]  — three chunks

collect([1, 1, 2, 2, 1, 1])->groupBy(fn ($v) => $v);
// [1 => [1, 1, 1, 1], 2 => [2, 2]]  — two groups

```

If non-adjacent items with the same value need to end up together, either sort the data first or use `groupBy()`. Keys are preserved inside each chunk; call `values()` if you need a zero-indexed list.

Streaming Large Datasets with `LazyCollection`
----------------------------------------------

`chunkBy()` is available on both standard and `LazyCollection`. On a lazy collection it yields each chunk as soon as the grouping value changes, keeping only the current chunk in memory at any time.

A practical example — exporting per-order CSVs from a table with millions of rows:

```php
use App\Models\LineItem;
use Illuminate\Support\Facades\Storage;

LineItem::query()
    ->orderBy('order_id')
    ->orderBy('id')
    ->cursor()
    ->chunkBy('order_id')
    ->each(function ($items) {
        $orderId = $items->first()->order_id;

        Storage::disk('exports')->put(
            "orders/{$orderId}.csv",
            $items->map(fn ($item) => implode(',', [
                $item->sku,
                $item->quantity,
                $item->unit_price,
            ]))->implode(PHP_EOL)
        );
    });

```

The `orderBy('order_id')` is not optional — `chunkBy()` relies on the data being sorted so the database handles ordering and PHP handles splitting, one row at a time.

The same pattern works over log files, paginated APIs, or any generator-based source that is too large to hold in memory.

Two Gotchas Worth Knowing
-------------------------

**Loose comparison.** The implementation uses `==`, not `===`. Mixed-type input like `['1', 1, 1.0]` lands in a single chunk. Normalize the return value from your callback when type consistency matters:

```php
$rows->chunkBy(fn ($row) => (string) $row['code']);

```

**The resolver runs twice per boundary.** Each boundary check resolves the current item and re-resolves the last item of the current chunk. For expensive operations (date parsing, hashing), precompute the value first:

```php
$entries
    ->map(fn ($entry) => [$entry, Carbon::parse($entry->logged_at)->toDateString()])
    ->chunkBy(fn ($pair) => $pair[1]);

```

For simple key or property lookups this overhead is negligible.

Key Takeaways
-------------

- `chunkBy('key')` is a readable shorthand for the common `chunkWhile()` pattern.
- It groups **adjacent** items only — sort your data first if you need global grouping.
- Dot-notation keys work via `data_get()`.
- On `LazyCollection` it streams chunk-by-chunk, keeping memory usage proportional to the largest single chunk.
- Comparisons are loose (`==`); cast return values when strict type matching is required.
- Contributed by [@JosephSilber](https://github.com/JosephSilber) in [\#61357](https://github.com/laravel/framework/pull/61357).

---

*Source: [Laravel News — Group Adjacent Collection Items in Laravel with chunkBy()](https://laravel-news.com/laravel-collection-chunk-by)*

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fmsaied.com%2Farticles%2Fgroup-adjacent-collection-items-in-laravel-with-chunkby&text=Group+Adjacent+Collection+Items+in+Laravel+with+chunkBy%28%29) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fmsaied.com%2Farticles%2Fgroup-adjacent-collection-items-in-laravel-with-chunkby) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  What is the difference between chunkBy() and groupBy() in Laravel?        chunkBy() groups only consecutive items that share the same key value, producing multiple chunks if the same value appears in non-adjacent positions. groupBy() collects all items with the same key regardless of their position, merging them into a single group. 

      Q02  Does chunkBy() work with LazyCollection for large datasets?        Yes. On a LazyCollection, chunkBy() yields each chunk as soon as the grouping value changes, so only the current chunk is held in memory at any time. Pair it with a cursor() query sorted by the grouping column for memory-efficient processing of large database tables. 

      Q03  Does chunkBy() use strict or loose comparison?        chunkBy() uses loose comparison (==), not strict (===). This means values like '1', 1, and 1.0 are treated as equal and land in the same chunk. Cast the return value of your callback to a consistent type if strict separation is needed. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://msaied.com/articles) 

 [ ![Laravel New in 13: Features, Helpers, and Upgrade Notes](https://cdn.msaied.com/625/629cfac34ade7206a215809c0438c5ae.png) laravel php upgrade 

### Laravel New in 13: Features, Helpers, and Upgrade Notes

Laravel 13 ships with async-first primitives, tightened type contracts, and quality-of-life helpers that rewar...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 3 Sep 2026     3 min read  

  Read    

 ](https://msaied.com/articles/laravel-new-in-13-features-helpers-and-upgrade-notes) [ ![Statamic Sidecar: Edit Markdown Sites from the Control Panel Without Migration](https://cdn.msaied.com/624/6df15b406d700ea26fb98c6ad4779195.png) Statamic Markdown CMS 

### Statamic Sidecar: Edit Markdown Sites from the Control Panel Without Migration

Statamic's new Sidecar product lets you manage any static site generator's Markdown files through the Statamic...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 2 Sep 2026     3 min read  

  Read    

 ](https://msaied.com/articles/statamic-sidecar-edit-markdown-sites-from-the-control-panel-without-migration) [ ![Laravel Macro-Free Extensibility: Extending Eloquent Builder with Custom Query Objects](https://cdn.msaied.com/621/b0c176a363378658e83bb44ed379879b.png) laravel eloquent clean-architecture 

### Laravel Macro-Free Extensibility: Extending Eloquent Builder with Custom Query Objects

Skip global macros and reach for typed, testable query objects that encapsulate reusable Eloquent constraints...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 2 Sep 2026     1 min read  

  Read    

 ](https://msaied.com/articles/laravel-macro-free-extensibility-extending-eloquent-builder-with-custom-query-objects) 

   [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

Explore

- [Home](https://msaied.com)
- [Projects](https://msaied.com/projects)
- [Articles](https://msaied.com/articles)
- [Certificates](https://msaied.com/certificates)
- [Contact](https://msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
