laravel collection get by key code example
Example 1: collection laravel filter
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all();
Example 2: laravel sort collection by key
$collection = collect([
['name' => 'Desk', 'price' => 200],
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
]);
$sorted = $collection->sortBy('price');
$sorted->values()->all();
Example 3: get item from collection that match
$artist = 'Vincent John Doe';
$art_collection = $paintings->filter(function ($painting) use ($artist) {
return $painting->artist == $artist;
});
foreach($paintings as $painting) {
if($painting->artist == $artist) {
$art_collection[] = $painting;
}
}
Example 4: laravel reduce
$collection = collect([1, 2, 3]);
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
});
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 4);