Laravel Collections Now Include A Partition Method

News

December 15th, 2016

collections-partion.png

A new feature that just arrived in Laravel 5.3 is a new Collection Partition method that allows you to separate results into two elements.

1$collection = collect([1, 2, 3, 4, 5, 6, 7]);
2
3$items = $collection->partition(function ($i) {
4 return $i < 4;
5});

Now $items will be a collection containing two items. The first is a collection of items that passed the callback, and the second for the ones that did not.

Here is a look at the results from the code above called through print_r:

1Illuminate\Support\Collection Object
2(
3 [items:protected] => Array
4 (
5 [0] => Illuminate\Support\Collection Object
6 (
7 [items:protected] => Array
8 (
9 [0] => 1
10 [1] => 2
11 [2] => 3
12 )
13
14 )
15
16 [1] => Illuminate\Support\Collection Object
17 (
18 [items:protected] => Array
19 (
20 [3] => 4
21 [4] => 5
22 [5] => 6
23 [6] => 7
24 )
25
26 )
27
28 )
29
30)

This method is available starting at v5.3.27 and you can run composer update to get the latest.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.