Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 854
Jakub Kohout Avatar asked Jul 21 '14 08:07

Jakub Kohout


People also ask

How do I get the latest 5 records in Laravel?

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.

How can get data from database in Laravel?

After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table. Run a select statement against the database.

How do I get my last month record from Laravel?

Laravel Get Last Month records Use the below laravel eloquent query to get the last month records from the database table. User::whereMonth('created_at', '=', Carbon::now()->subMonth()->month)->get(['name','created_at']); This query uses laravel method whereMonth() and get().


2 Answers

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(); 
like image 138
The Alpha Avatar answered Oct 06 '22 11:10

The Alpha


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.

like image 41
parker_codes Avatar answered Oct 06 '22 10:10

parker_codes