There are many cases where we need to get only the last record of the table in our project. Getting the latest record of a database table in Laravel can be a simple process when you know the right methods to use.
In this article, we’ll explore how to use Laravel’s ORM layer to get the latest record from a database table. We’ll discuss different methods of retrieving data, and how to use them to get the most up-to-date information from your database.
We can retrieve the latest record of a table using latest()
, orderBy()
, and first()
methods.
Here are several ways to achieve the result depending 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.
The latest()
method is called on the query builder instance to order the results by the “created_at” column in descending order (assuming that the “created_at” column exists in the “users” table). Then, the first()
method is called to retrieve only the first result from the ordered list, which will be the latest user record in the table.