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

// [3, 4]

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

/*
    [
        ['name' => 'Chair', 'price' => 100],
        ['name' => 'Bookcase', 'price' => 150],
        ['name' => 'Desk', 'price' => 200],
    ]
*/

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;
  }
}

Example 4: laravel reduce

$collection = collect([1, 2, 3]);

$total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
});

// 6

$total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
}, 4);

// 10   | where 4 is a initial value

Tags:

Php Example