Laravel Collection Public API: first

November 29, 2016 —John Koster

first(callable $callback = null, $default = null)

The first method is used to get the first item in a collection, or to get the first item in a collection that matches a set of criteria. A $callback can be supplied to return the first item in the collection that matches a given truth test. Additionally, an optional $default argument can be passed that will be returned if there are no items that match the given criteria.

The following example shows how to get the first item in a collection:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'first', 'second', 'third'
8]);
9 
10// first
11$value = $collection->first();

If the collection is empty (having no items), the first method will return null:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create an empty collection.
6$collection = new Collection([]);
7 
8// null
9$value = $collection->first();

The $default parameter cannot be used when trying to get the first item in an empty collection:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create an empty collection.
6$collection = new Collection([]);
7 
8// null
9$value = $collection->first(null, 'default-value');

A $callback argument can be passed to provide a truth test when evaluating which item should be returned first:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'first', 'second', 'third'
8]);
9 
10// second
11$value = $collection->first(function($key, $value) {
12 return strlen($value) > 5;
13});

The $default parameter can be used in conjunction with the $callback parameter to return a default value when there are no items in a collection that pass the given truth test:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// null
6$value = $collection->first(function($key, $value) {
7 return strlen($value) > 10;
8});
9 
10// default-value
11$value = $collection->first(function($key, $value) {
12 return strlen($value) > 10;
13}, 'default-value');

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.