Laravel: How to get last N entries from DB
Dogs::orderBy('created_at','desc')->take(5)->get();
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();
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.
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.