PASSWORD RESET

Your destination for complete Tech news

PHP

How to get the last item from a collection in Laravel?

682 0
< 1 min read

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.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.