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.
Related Tips
View all tips →Simplify Collection Operations with Higher-Order Messages
Laravel Collections support higher-order messages through dynamic properties, allowing operations like each, map, filter, and groupBy to work directly with an item's property or method without writing boilerplate callbacks.
Dynamic Date Grouping in Laravel Collections Using Closures in groupBy()
Pass a closure to Laravel Collection's groupBy() method to group models and arrays dynamically by day, week, month, or quarter.