Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel collection filter by condition and split

Tags:

php

laravel

I have a collection and each item has a featured attribute which is either true or false, so I want to get two variables $featured and $unfeatured.

I can do this:

$featured = $collection.filter(function($item){
   return $item->featured;
});

$unfeatured = $collection.filter(function($item){
   return !$item->featured;
});

But maybe there's a shorter way?

like image 217
nick Avatar asked Oct 04 '17 01:10

nick


2 Answers

I know this is quite an old post. Thought I would add this for folks coming to this from search.

Since 5.3 you can use the partition method like so:

list($featured, $unfeatured) = $collection->partition(function($item) {
    return $item->featured;
});

https://laravel.com/docs/5.3/collections#method-partition

like image 93
space-goat Avatar answered Sep 19 '22 17:09

space-goat


You could use the each() method

$featured = [];
$unfeatured = [];

$collection->each(function ($item) use (&$featured, &$unfeatured) {
    if ($item->featured) {
        $featured[] = $item;
    } else {
        $unfeatured[] = $item;
    }
}
like image 37
linktoahref Avatar answered Sep 23 '22 17:09

linktoahref