Posts Learn Components Snippets Categories Tags Tools About

How to Get Last Record (Row) in Laravel

Learn how to get the last record or row in Laravel using the Eloquent Model and DB facade the easy way

Created on Oct 22, 2021


Sometimes you might find the need of getting the last record row in Laravel and to achieve this you can either use Eloquent Model or DB facade.

Using Eloquent Model To Get Last Record

To get the last record using Laravel Eloquent you can call the model directly for example "Post" and then chain it with the "latest()" model. Other than that you can also get the whole collection and get the last item, and finally by ordering the post in descending order by ID then getting the first result.

/* Directly Querying The Model */

/* Getting Collection and Take Last Item*/

/* Order the Post by Descending and get First Item */
    ->orderBy('id', 'desc')

Using Eloquent Model to Get Last Record ID

to get the last record ID you can directly chain the call "->id" property from the object instance itself.


You might be wondering what about UUID, will this method worK? and the answer to that is that it's possible to get the latest by UUID as well.

/* get latest by the UUID */

Using DB Facade to get Last Record in Laravel

If you do prefer more to use DB facade (fluent) then you can write your code as follows. You can make use of the "last()" method as well as the "latest()" method to get the last record.

use \DB;

/* Get the last post [which is essentially the last record]*/

/* To access the property just chain the column */

/* Another Approach */
By now you should be able to get the last / latest record in Laravel using Eloquent / Fluent. If you do find this tutorial to be helpful do make sure to share it with your friends, cheers!

Recommended Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Get Last Record (Row) in Laravel