Laravel: How to take the last lines of n (any number) after ordered in ascending order?

  • I have 3 id , msg and created_at in my model table. created_at is the timestamp, and id is the primary key.
  • I also have 5 data, world => time4 , hello => time2 , haha => time1 , hihio => time5 and dunno => time3 , and this data is arranged in ascending order (as described here) based on their id .

In laravel 4 I want to get this data, sort it in ascending order and take the last n (in this case, 3) number of records. So, I want the dunno , world and hihio be displayed as follows in a div:

 dunno,time3 world,time4 hihio,time5 

What i tried

 Model::orderBy('created_at','asc')->take(3); 

unwanted result:

 haha,time1 hello,time2 dunno,time3 

Also tried

 Model::orderBy('created_at','desc')->take(3); 

unwanted result:

 hihio,time5 world,time4 dunno,time3 

I also tried the opposite with no luck

 Model::take(3)->orderBy('created_at','asc'); 

This problem seems pretty simple, but I just can't figure out my logic. I'm still pretty new to Laravel 4, so I would give bonus points to better solutions than using orderBy() and take() , if any. Thank you very much!

+8
sorting php mysql laravel laravel-4
source share
2 answers

You are very close.

It looks like you want to order the array first in descending order

  Model::orderBy('created_at','desc')->take(3); 

but then change the array. You can do this in one of two ways: either traditional PHP (using array_reverse).

  $_dates = Model::orderBy('created_at','desc')->take(3); $dates = array_reverse($_dates); 

Or the laravel path using the reverse function in the Laravel Collection class.

  $_dates = Model::orderBy('created_at','desc')->take(3)->reverse(); 

Check out the Laravel Collection documentation on your API website at http://laravel.com/api/class-Illuminate.Support.Collection.html

Now $ date will contain the desired result.

 dunno,time3 world,time4 hihio,time5 
+7
source share

You're right next to your second attempt. After retrieving the rows from the database, you just need to undo the array. Assuming you have an instance of Illuminate\Support\Collection , you just need the following:

 $expectedResult = $collection->reverse(); 
+3
source share

All Articles