Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 and Eloquent ORM - How to select the last 5 rows of a table

I'm trying to figure out how to select the last 5 rows of a table to display on a home screen when there might be gaps in the ids. The database this is for has 1,000s of rows and I don't want to have to call all of them to take the last 5 every time I go to my app's home screen. The problem is that rows sometimes are deleted in the database for various reasons so, for example, if the last row's id is 4023 the second to last row's id might be 4020, so I can't just use the length and count backwards. Ideally it would work like

$get_5_rows = DB::table('rows')->take(5)->get();

Except that instead of collecting the first 5 rows that it would take the last 5.

Thank y'all so much for the help! Any and all help is greatly appreciated!

like image 510
mario Avatar asked Jan 11 '23 17:01

mario


1 Answers

You may try this:

$rows = DB::table('rows')->orderBy('id', 'desc')->take(5)->get();

You may also use orderBy('created_at') if that field is available. Another similar answer here.

like image 128
The Alpha Avatar answered Jan 22 '23 12:01

The Alpha