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

7719 views

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.
<?php

/* Directly Querying The Model */
Post::query()
    ->latest()
    ->first();

/* Getting Collection and Take Last Item*/
Post::all()->last();

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

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.
<?php

Post::query()
    ->latest()
    ->first()
    ->id;

Post::all()->last()->id;
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.
<?php

/* get latest by the UUID */
Post::query()
    ->latest('uuid')
    ->first();

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.
<?php

use \DB;

/* Get the last post [which is essentially the last record]*/
DB::table('posts')->get()->last();

/* To access the property just chain the column */
DB::table('posts')->get()->last()->id;

/* Another Approach */
DB::table('posts')->latest('published_at')->first();
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

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours
)