November 29, 2016 —John Koster
last(callable $callback = null, $default = null)
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.
The following example shows how to get the last 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// third11$value = $collection->last();
If the collection is empty (having no items), the last
method will return null
:
1<?php2 3use Illuminate\Support\Collection;4 5// Create an empty collection.6$collection = new Collection([]);7 8// null9$value = $collection->last();
The $default
parameter cannot be used when trying to get the last item in an empty collection:
1<?php2 3use Illuminate\Support\Collection;4 5// Create an empty collection.6$collection = new Collection([]);7 8// null9$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:
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// second11$value = $collection->last(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->last(function($key, $value) { 7 return strlen($value) > 10; 8}); 9 10// default-value11$value = $collection->last(function($key, $value) {12 return strlen($value) > 10;13}, 'default-value');
∎
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.