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();

// [3, 4]

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();

/*
    [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

Example 3: get item from collection that match

$artist = 'Vincent John Doe';

// you can filter the collection and keep only those items
// that pass a given truth test:
$art_collection = $paintings->filter(function ($painting) use ($artist) {
  return $painting->artist == $artist;
});

// you can also do a foreach
foreach($paintings as $painting) {
  if($painting->artist == $artist) {
    $art_collection[] = $painting;
  }
}

Tags:

Php Example