Friday, January 17, 2020

How to get last record of database table in Laravel?


Sometimes we may request to get only the last record of the table in our project, we can get it in
several ways. We can get the last record in the database table using latest () or orderBy (). In the following example, you can see how I get the last record in the table.
I have an "elements" table and I want to get the last record of the "elements" table. In the first example, use latest () with first () because latest () will only look for the last record based on created_at, so first () will get only one 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();

0 comments:

Post a Comment

Please don't enter any spam link in the comment box.