How to Split a Collection in Laravel 8
Arie Visser • November 25, 2020
laravel phpSince Laravel 8.16, it is possible to split a collection into chunks in two different ways.
The split
method
The first one, that already existed, is the split method:
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$groups = $collection->split(3);
$groups->all();
// [[1, 2, 3], [4, 5], [6,7]]
This method breaks a collection into a specified amount of groups.
As you can see, it tries to keep the amount of items in each group as close together as possible.
The difference will never be more than one.
In the example above, this leads to 3 chunks with sizes 3, 2, and 2.
The splitIn
method
What if you want to split a collection into groups of similar size, and put the remainder in the last group?
This is why splitIn was introduced in the 8.16.0 release.
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$groups = $collection->splitIn(3);
$groups->all();
// [[1, 2, 3], [4, 5, 6], [7]]
It works almost the same, except that the collection will now be split into 2 groups of sizes 3, and 1 group with the remaining item.
Example tests can be found in this repository.