Laravel Collections

Group Consecutive Items with chunkBy()

Punyapal Shah 1 min read
edit this tip
Use chunkBy() to split a Collection whenever the resolved value changes, without manually comparing items with the previous chunk.

Before Laravel 13.30, grouping consecutive items with the same value could require chunkWhile():

$products->chunkWhile(
    fn (Product $product, $key, $chunk) =>
        $product->status === $chunk->last()->status
);

Laravel 13.30 adds chunkBy() for this pattern:

$products->chunkBy('status');

You can also provide a callback when the value needs to be calculated:

$products->chunkBy(
    fn (Product $product) => $product->status
);

The important difference from groupBy() is that chunkBy() keeps consecutive values together. If the same value appears again later, it starts a new chunk:

collect(['paid', 'paid', 'pending', 'pending', 'paid'])
    ->chunkBy(fn (string $status) => $status)
    ->all();

// [
//     ['paid', 'paid'],
//     ['pending', 'pending'],
//     ['paid'],
// ]

It also works with nested attributes:

$orders->chunkBy('customer.id');

Use chunkBy() when the order of the items matters and you want to split them into consecutive groups based on a value.

Tags: Laravel Collections PHP
Share on

// Found an issue or want to contribute a tip? github.com/MrPunyapal/tips