How do you retrieve the last item of a collection in Laravel?

How do you retrieve the last item of a collection in Laravel?

 

In Laravel, retrieving the last item from a collection is straightforward using the last() method. Here’s an example:

Example

<?php
$lastItem = $collection->last();
?>

This will return the last item from the $collection. It’s particularly useful when you’re working with a Laravel collection object, as it allows you to access the final element in the dataset effortlessly.

If you’re working with a query and want to fetch the latest record, you can use the latest() method or a custom ordering. For instance:

Example

<?php
$lastItem = Model::latest()->first();
?>

This will return the most recently created record based on the created_at field. Alternatively, you can manually order the query by any other column, such as:

Example

<?php
$lastItem = Model::orderBy('created_at', 'desc')->first();
?>

In both cases, the result will be the last record according to the specified order criteria.

Related Questions & Topics

Powered and designed by igetvapeaustore.com | © 2024 codestap.com.