Laravel 13.30 New Published on

Grouping adjacent items with chunkBy()

Consecutive messages from the same author are grouped into one line, without a loop or a tracking variable.

Topics covered: Collections

New in Laravel 13.30. To split a collection every time a value changes, you needed a loop with a tracking variable, or chunkWhile() and a function comparing each item to the last one of the chunk. chunkBy() does this split directly.

Before

$messages->chunkWhile(
    fn (array $message, int $key, Collection $chunk) => $message['author'] === $chunk->last()['author']
);

Since Laravel 13.30

$messages->chunkBy('author');

chunkBy() accepts a key or a function. It isn't groupBy(): only adjacent items that share the same value are grouped. An author who speaks again later therefore opens a new group.

Your task

FilDeMessages::groupByAuthor() groups consecutive messages from the same author, to display them as in a messaging app. Rewrite this method with chunkBy(), without a loop. The result must stay the same: a list of groups ['author' => …, 'messages' => [texts…]].

Where the feature comes from: the original pull request.