laravel get values from collection 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 collection group by
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->toArray();
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;
}
}