Laravel: How to get last N entries from DB
94,017
Solution 1
You may try something like this:
$dogs = Dogs::orderBy('id', 'desc')->take(5)->get();
Use orderBy
with Descending
order and take the first n
numbers of records.
Update (Since the latest
method has been added):
$dogs = Dogs::latest()->take(5)->get();
Solution 2
My solution for cleanliness is:
Dogs::latest()->take(5)->get();
It's the same as other answers, just with using built-in methods to handle common practices.
Solution 3
Dogs::orderBy('created_at','desc')->take(5)->get();
Solution 4
You can pass a negative integer n to take the last n elements.
Dogs::all()->take(-5)
This is good because you don't use orderBy which is bad when you have a big table.
Solution 5
You may also try like this:
$recentPost = Article::orderBy('id', 'desc')->limit(5)->get();
It's working fine for me in Laravel 5.6
Author by
Jakub Kohout
Updated on October 06, 2021Comments
-
Jakub Kohout over 2 years
I have table of dogs in my DB and I want to retrieve
N latest added dogs
.Only way that I found is something like this:
Dogs:all()->where(time, <=, another_time);
Is there another way how to do it? For example something like this
Dogs:latest(5);
Thank you very much for any help :)
-
f7n about 7 yearsWhat happens if there are only 3 records in this case?
-
The Alpha about 7 yearsYou'll get three :-)
-
ibnɘꟻ over 5 yearsYes, method
take
andlimit
is similar. The parent islimit
, andtake
is just alias. You can check on file Builder.php -
TrueStory over 4 yearsThis will reverse order of your items. You will have to re-order them in your application. So if you're trying to load last 5 posts sorted by date, don't forget to re-sort them on collection level.
-
iSWORD over 4 yearsThis also works with UUIDs so it's more generic. It doesn't work with tables that don't have timestamps though.
-
Luca C. over 3 yearsit is not warranted that the last 5 resulted are the last 5 inserted. it USUALLY works, but with no warranty
-
M at about 3 yearsI had no success using it. To me -5 and 5 works the same !!!
-
Lizesh Shakya over 2 yearsYour answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.