php - Laravel: Kuinka saada viimeiset N merkinnät DB: stä

original title: "php - Laravel: How to get last N entries from DB"


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 :)

Minulla on koirataulukko tietokannassani ja haluan noutaa N viimeksi lisättyä koiraa. Ainoa tapa, jolla löysin, on jotain tällaista: Koirat: kaikki () -> missä (aika, <=, toinen aika); Onko th ...

Tämä on yhteenveto käännöksen jälkeen. Jos haluat tarkastella koko käännöstä, napsauta käännä-kuvaketta

Kaikki vastaukset
  • Translate

    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.

  • Translate

    My solution for cleanliness is:


    It's the same as other answers, just with using built-in methods to handle common practices.

  • Translate

  • Translate

    You may also try like this:

    $recentPost = Article::orderBy('id', 'desc')->limit(5)->get();

    It's working fine for me in Laravel 5.6

  • Translate

    You can pass a negative integer n to take the last n elements.


    This is good because you don't use orderBy which is bad when you have a big table.

  • Translate

    Ive come up with a solution that helps me achieve the same result using the array_slice() method. In my code I did array_slice( PickupResults::where('playerID', $this->getPlayerID())->get()->toArray(), -5 ); with -5 I wanted the last 5 results of the query.