In Laravel, you can use the last method of the Collection class to get the last item from a collection.
Here’s an example of how you can use it:
$collection = collect([1, 2, 3]);
$last = $collection->last();
echo $last; // Outputs: 3
You can also pass a callback function to the last method to determine which item should be considered the last:
$collection = collect([
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane'],
['id' => 3, 'name' => 'Bob'],
]);
$last = $collection->last(function ($item) {
return $item['id'] > 1;
});
echo $last['name']; // Outputs: Bob
In this example, the last method returns the last item in the collection that has an id greater than 1.
Note that the last method returns the last item in the collection, or null if the collection is empty. It does not modify the collection itself.
