laravel collection where function 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 methods

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

$collection->each(function($item){
    return $item*$item;
});

// [1,4,9,16]

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: collection methods laravel

$collection->each(function ($item, $key) {
    hj
});

Tags:

Php Example