Laravel chunkBy(): Group Adjacent Collection Items | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. [Laravel](https://www.msaied.com/public/articles?category=laravel)
6. /
7. Group Adjacent Collection Items in Laravel with chunkBy()

   [Laravel](https://www.msaied.com/public/articles?category=laravel) [Tips &amp; Tricks](https://www.msaied.com/public/articles?category=tips-tricks) 

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

 Laravel 13.30 adds chunkBy(), a clean shorthand for chunkWhile() that groups consecutive collection items sharing the same key value — with full LazyCollection support for memory-efficient streaming.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 3 Sep 2026 · Updated 3 Sep 2026 · 3 min read

ShareCopy linkCopied

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

  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)

 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)*

- [Laravel](https://www.msaied.com/public/articles?search=Laravel)
- [Collections](https://www.msaied.com/public/articles?search=Collections)
- [LazyCollection](https://www.msaied.com/public/articles?search=LazyCollection)
- [Laravel 13](https://www.msaied.com/public/articles?search=Laravel%2013)
- [Performance](https://www.msaied.com/public/articles?search=Performance)

 Frequently asked questions 
---------------------------

  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.

   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.

   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.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

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

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleStatamic Sidecar: Edit Markdown Sites from the Control Panel Without Migration](https://www.msaied.com/public/articles/statamic-sidecar-edit-markdown-sites-from-the-control-panel-without-migration) [Next articleLaravel New in 13: Features, Helpers, and Upgrade Notes](https://www.msaied.com/public/articles/laravel-new-in-13-features-helpers-and-upgrade-notes)  

   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)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
