Published in Laravel 5

Laravel 5 Collections: Getting the Last Collection Element With last

By John Koster

The last method is the logical opposite of the first method, and is used to get the last item in a collection, or to get the last item in a collection that matches a certain criteria. A $callback can be supplied to return the last 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.

#Signature

1public function last(
2 callable $callback = null,
3 $default = null
4);

#Example Use

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

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

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

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

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

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

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

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

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:

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