grabbing first object from collection laravel code example

Example 1: 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 2: collection get first element laravel

$first = $msgs->first(); // this does ->take(1) under the hood

Tags:

Php Example