Home / Snippets / How to Get Last Record (Row) in Laravel
How to Get Last Record (Row) in Laravel cover

How to Get Last Record (Row) in Laravel

7.8K

2 years ago

0 comments

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

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this