News

Laravel Collections Now Include A Partition Method

Published
Laravel Collections Now Include A Partition Method image

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.

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

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:

Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
 
)
 
[1] => Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
 
)
 
)
 
)

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

Eric L. Barnes photo

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

Sponsored

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
Decide with Jev: Laravel AI That Answers with a Probability image

Decide with Jev: Laravel AI That Answers with a Probability

Read article
JetBrains Air: Run AI Coding Agents in JetBrains IDEs image

JetBrains Air: Run AI Coding Agents in JetBrains IDEs

Read article
Memoize Tagged Cache Reads in Laravel image

Memoize Tagged Cache Reads in Laravel

Read article
Eloquent Refreshes: Load Generated Columns After Save image

Eloquent Refreshes: Load Generated Columns After Save

Read article
Laravel AI SDK 1.0 Adds Classification and Tool Approvals image

Laravel AI SDK 1.0 Adds Classification and Tool Approvals

Read article
Tagged Memoized Cache and Model Refreshes in Laravel 13.33 image

Tagged Memoized Cache and Model Refreshes in Laravel 13.33

Read article