How to get last record of database table in Laravel?

Today now in this post i will show you How to get last record of database table in Laravel? Sometimes we may need to get the only last record of table in our laravel application. We can easily get this on several way. Ypu can fetch the last record from database table by using latest() or orderBy().Now In the bellow example we can see how to we will get the last record of table.

Now here this is a very simple example of how to get last record from tabel in laravel 6, laravel 7 and laravel 8 any appliction.

Here I have on table “items” and i want to get the last record of “items” table. Now in first example i will use latest() also with first() because latest() will fetch the only latest record on according to created_at then first() will get the only single record:

Using latest() belong to created_at field:
$last = DB::table('items')->latest()->first();

Now, also In this example i will used orderBy() on that belong to id, it will always return the max id record:

Using orderBy() belong to id field:
$last2 = DB::table('items')->orderBy('id', 'DESC')->first();

Also in this example i will show use latest() with argument, latest() will take the created_at by default, if we want to give id then we need to give argument as field name.

Using latest() belong to id field:
$last3 = DB::table('items')->latest('id')->first();

Read Also: How to convert file extension using CloudConvert in laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →