Laravel : How to take last n(any number) rows after ordered in ascending order?
Solution 1
You are very close.
It sounds like you want to first order the array by descending order
Model::orderBy('created_at','desc')->take(3);
but then reverse the array. You can do this one of two ways, either the traditional PHP (using array_reverse).
$_dates = Model::orderBy('created_at','desc')->take(3);
$dates = array_reverse($_dates);
Or the laravel way, using the reverse
function in Laravel's Collection
class.
$_dates = Model::orderBy('created_at','desc')->take(3)->reverse();
Check out Laravel's Collection
documentation at their API site at http://laravel.com/api/class-Illuminate.Support.Collection.html
Now $dates will contain the output you desire.
dunno,time3
world,time4
hihio,time5
Solution 2
You're pretty close with your second attempt. After retrieving the rows from the database, you just need to reverse the array. Assuming you have an instance of Illuminate\Support\Collection
, you just need to the following:
$expectedResult = $collection->reverse();
Solution 3
To get last three rows in ascending order:
$_dates = Model::orderBy('created_at','desc')->take(3)->reverse();
Now, the json output of $_dates will give you a object of objects.
To get array of objects use:
$_dates = Model::orderBy('created_at','desc')->take(3)->reverse()->values();
Related videos on Youtube
John Evans Solachuk
Updated on September 15, 2022Comments
-
John Evans Solachuk almost 2 years
- I have 3 columns
id
,msg
andcreated_at
in my Model table.created_at
is a timestamp andid
is primary key. - I also have 5 datas,
world => time4
,hello => time2
,haha => time1
,hihio => time5
anddunno => time3
and these datas are arranged in ascending order (as arranged here) based on theirid
.
In laravel 4, I want to fetch these data, arrange them in ascending order and take the last n(in this case, 3) number of records. So, I want to get
dunno
,world
andhihio
rows displayed like this in a div :dunno,time3 world,time4 hihio,time5
What I have tried
Model::orderBy('created_at','asc')->take(3);
undesired result :
haha,time1 hello,time2 dunno,time3
Also tried
Model::orderBy('created_at','desc')->take(3);
undesired result :
hihio,time5 world,time4 dunno,time3
I have also tried the reverse with no luck
Model::take(3)->orderBy('created_at','asc');
This problem seems fairly simple but I just can't seem to get my logic right. I'm still fairly new in Laravel 4 so I would give bonus points to better solutions than using
orderBy()
andtake()
if there is. Thank you very much!-
Kemal Fadillah about 10 yearsUse
orderBy('created_at', 'desc')->take(3)
, and then reverse the array.
- I have 3 columns