How to get last / latest record of database in Laravel?

By Ved Prakash N | Apr 26, 2023 | Laravel
Share :

https://www.fundaofwebit.com/post/how-to-get-latest-record-by-id-in-laravel

How to get last record of database table in Laravel?


Hi guys, 

In this post, we will be learning about how to get the LAST or LATEST record from database in laravel.

So, there are many ways to get the Latest / LAST record in Laravel 10 / 9 / 8.

We are normally used latest() eloquent function to getting latest data with created_at default column. but if you need with another column like published_at or something else.

So guys, lets start to get last record in laravel.


Method 1: Using latest() belong to created_at field:

$product = Product::latest()->first();

Lets use the latest() function but with the custom optional database column name as follows:

$product = Product::latest('published_at')->first();


Method 2: Using orderBy() belong to id field:

$product = Product::orderBy('id', 'DESC')->first();


Method 3: using get() with latest(). It will get the last record

$product = Product::get()->latest();


Method 4: using get() with last(). It will get the last record

$product = Product::get()->last();


I hope, It will help you.

https://www.fundaofwebit.com/post/how-to-get-latest-record-by-id-in-laravel

Share this blog on social platforms