Skip to main content

How to Get the Latest Record from a Table in Laravel

In this snippet, we will discuss how to get the latest record of a database table in Laravel. Laravel offers Eloquent ORM which is very simple and easy to use. With the help of Eloquent ORM, we can perform all CRUD operations on database tables.

We can get the latest record of the database table using the orderBy() method of Eloquent ORM. The orderBy() method accepts two parameters, column name, and sorting order. The column name is the name of the column on which we want to sort the data and the sorting order can be either ‘ASC’ or ‘DESC’.

Another way is to use latest() method of Eloquent ORM. The latest() method accepts the column name on which we want to sort the data and returns the first record of the database table.

So, let’s see how to get the latest record of a database table in Laravel with an example.

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

$language = ProgrammingLanguage::latest()->first();
$language = ProgrammingLanguage::select('id')->where('type', $type)->latest('id')->first();
$language = ProgrammingLanguage::orderBy('created_at', 'desc')->first();

$language = ProgrammingLanguage::all()->last();
$type = ProgrammingLanguage::all()->last()->pluck('type');
$latest_id = ProgrammingLanguage::all()->last()->id;
$latest_id = ProgrammingLanguage::orderBy('id', 'desc')->first()->id;

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