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

11,744

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();
Share:
11,744

Related videos on Youtube

John Evans Solachuk
Author by

John Evans Solachuk

Updated on September 15, 2022

Comments

  • John Evans Solachuk
    John Evans Solachuk 3 months
    1. I have 3 columns id, msg and created_at in my Model table. created_at is a timestamp and id is primary key.
    2. I also have 5 datas, world => time4, hello => time2,haha => time1,hihio => time5 and dunno => time3 and these datas are arranged in ascending order (as arranged here) based on their id.

    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 and hihio 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() and take() if there is. Thank you very much!

    • Kemal Fadillah
      Kemal Fadillah over 8 years
      Use orderBy('created_at', 'desc')->take(3), and then reverse the array.