Laravel: How to get last N entries from DB

Jakub Kohout picture Jakub Kohout · Jul 21, 2014 · Viewed 62k times · Source

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

Answer

The Alpha picture The Alpha · Jul 21, 2014

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.