How to get latest record of database table in Laravel?

There are many cases where we need to get only last record of table in our project. We can retrieve the latest record of a table using latest() or orderBy()

Here are several ways to achieve the result depends on what you choose to use for database persistence.

$user = DB::table('users')->latest()->first();
$user = DB::table('users')->orderBy('id', 'DESC')->first();

$user = User::latest()->first();
$user = User::select('id')->where('username', $username)->latest('id')->first();
$user = User::orderBy('created_at', 'desc')->first();

$user = User::all()->last();
$username = User::all()->last()->pluck('username');
$latest_id = User::all()->last()->id;
$latest_id = User::orderBy('id', 'desc')->first()->id;

Don’t use all() method if your table has lots of data.

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close