How To Get Last Record of Database Table in Laravel 8

Share this Article
Reading Time: 3 minutes
3,748 Views

Inside this article we will see the concept i.e How to get last record of database table in laravel 8. 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 8 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

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

$ composer create-project --prefer-dist laravel/laravel blog

To start the development server of Laravel –

$ php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.


Concept: Last Row Data (Laravel 8 Methods)

We have options to get exact the last row from any database table in laravel 8.

  • 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 How To Get Last Record of Database Table in Laravel 8 Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5