Laravel 9 How To Get Last Record of Database Table

Reading Time: 3 minutes
2,891 Views

Inside this article we will see the concept i.e laravel 9 How to get last record of database table. Article contains classified information about getting last record from database table.

Laravel provides several option to get the last or we can say the latest row of table. We will assume that we have a table and from that we want the last inserted row using laravel 9 methods.

If you are looking for an article which gives you understanding about getting last row data from database table then this article is best for you.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Methods: Get Last Row Data

We have options to get exact the last row from any database table in laravel 9 are:

  • Using latest() Method
  • Using orderBy() Method

Suppose we have a students table in which 100 rows are there.

Using latest() Method

latest() method get the last row inserted from a table. It works on the basis of created_at timestamp column.

We use latest() method with first() to get the single row data.

Query #1: Get last row from students table on the basis of created_at column

$last_row = DB::table('students')->latest()->first();

Query #2: Get last row from students table on the basis of id column

$last_row = DB::table('students')->latest("id")->first();

Using orderBy() Method

Second method we have using orderBy(). On the basis of descending order of id value, we can get the last row from table.

$last_row = DB::table('students')->orderBy('id', 'DESC')->first();

We hope this article helped you to learn Laravel 9 How To Get Last Record of Database Table Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.