How to Get last 1, 5, 10 or more records of database table in Laravel?

December 22, 2022
Laravel
How to Get last 1, 5, 10 or more records of database table in Laravel?

In this quick tutorial, you will learn how to get the last 1 record, last 5 records, last 10 records or n number of records in laravel.

We will discuss 2 ways of getting the last records using latest() and orderBy() eloquent function in laravel.

Also this tutorial is valid for laravel 6, laravel 7, laravel 8 and laravel 9 as well.

So lets get started.

Assumption:

Let’s assume that I have Article Model which is tied with article table.

How to Get last 1 record of table in Laravel?

There are two methods to get the last record of the table.

a) Using latest()

In this part, we will using the latest(). Type the following code into your controller.

Article::latest()->first();

In the above code, latest() is the method that sort the data desc based on the created_at column. And first() is used to get the first row itself. So this will get the last 1 record of the table.

b) Using OrderBy()

We can also fetch the using orderBy() method in order to get last record from the table

Article::orderBy('created_at','desc')->first();

In the above code, same as the latest(), we are applying the orderby() on the created_at and sorting it on desc then getting the first row using first() method which will be eventually last row since the we have sorted on descending.

How to Get last 5 records of table in Laravel?

We will using orderBy() and take() to get the last 5 records of the table in laravel.

Article::orderBy('created_at','desc')->take(5)->get();

In the above code, first we are ordering by descending on created_at the column then we are using take() method in which we are specifying how many rows we want. Since we want 5, that why we mentioned 5 as the argument.

How to Get last 10 records of table in Laravel?

Similar to the last 5 records, we will using orderBy() and take() again in order to get the last 10 records from the database table in laravel.

Article::orderBy('created_at','desc')->take(10)->get();

The above code will first sort the rows by created_at column in the descending order and will take 10 records using take(10).

How to Get last N records or entries of table in Laravel?

To get last n numer of records from table in laravel, we have once again use orderBy() and take().

$n=50;
Article::orderBy('created_at','desc')->take($n)->get();

In the above code, we have declared n a variable which can be any number you want to get last rows of. So in my case, I want to fetch last 50 records, so that why i set n to be 50.

Conclusion

Hope the above article you have learned how to get the last 1, 5, 10 or n number of entries/records in laravel.

Let me know if you have any questions in the comments.


Write a Reply or Comment

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


Icon