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
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.
Let’s assume that I have
Article Model which is tied with
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.
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
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
take() to get the last 5 records of the table in laravel.
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
take() again in order to get the last 10 records from the database table in laravel.
The above code will first sort the rows by
created_at column in the descending order and will take 10 records using
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
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.
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.