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?
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
You could use the each()
method
$featured = [];
$unfeatured = [];
$collection->each(function ($item) use (&$featured, &$unfeatured) {
if ($item->featured) {
$featured[] = $item;
} else {
$unfeatured[] = $item;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With