How to get last record of database table in Laravel?

How to get last record of database table in Laravel?

In this post we will give you information about How to get last record of database table in Laravel?. Hear we will give you detail about How to get last record of database table in Laravel?And how to use it also give you demo for it if it is necessary.

Sometimes we may require to get only last record of table in our project, we can get several way. We can fetch last record of database table using latest() or orderBy(). In bellow example you can see how i get then last record of table.

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

Using latest() belong to created_at field:

$last = DB::table('items')->latest()->first();

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

Using orderBy() belong to id field:

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

In this example latest() with argument, latest() will take created_at by default, if you want to give id then you can give argument as field name.

Using latest() belong to id field:

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

But If you want to get last inserted id then you have to follow this link :

How to get last inserted id in laravel 5?.

Hope this code and post will helped you for implement How to get last record of database table in Laravel?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  73  =  83

We accept paid advance and paid guest Posting on our Site : Contact US