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

Share:
94,017
Jakub Kohout
Author by

Jakub Kohout

Updated on October 06, 2021

Comments

  • Jakub Kohout
    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
    f7n about 7 years
    What happens if there are only 3 records in this case?
  • The Alpha
    The Alpha about 7 years
    You'll get three :-)
  • ibnɘꟻ
    ibnɘꟻ over 5 years
    Yes, method take and limit is similar. The parent is limit, and take is just alias. You can check on file Builder.php
  • TrueStory
    TrueStory over 4 years
    This 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
    iSWORD over 4 years
    This also works with UUIDs so it's more generic. It doesn't work with tables that don't have timestamps though.
  • Luca C.
    Luca C. over 3 years
    it is not warranted that the last 5 resulted are the last 5 inserted. it USUALLY works, but with no warranty
  • M at
    M at about 3 years
    I had no success using it. To me -5 and 5 works the same !!!
  • Lizesh Shakya
    Lizesh Shakya over 2 years
    Your 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.