PASSWORD RESET

Your destination for complete Tech news

How to get the last item in Laravel collection?

496 0
< 1 min read

To get the last item in a Laravel collection, you can use the last method. This method will return the last element of the collection, or null if the collection is empty.

Here’s an example:

$collection = collect([1, 2, 3, 4, 5]);
$last = $collection->last();

// $last is now 5

You can also pass a callback to the last method to get the last element that matches a certain condition:

$collection = collect([1, 2, 3, 4, 5]);
$last = $collection->last(function ($value, $key) {
    return $value > 3;
});

// $last is now 5

If you want to get the last element and remove it from the collection, you can use the pop method:

$collection = collect([1, 2, 3, 4, 5]);
$last = $collection->pop();

// $last is now 5
// $collection is now [1, 2, 3, 4]

Leave A Reply

Your email address will not be published.

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