Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  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!

like image 479
John Evans Solachuk Avatar asked Jun 11 '14 03:06

John Evans Solachuk


People also ask

How can I get last record in laravel?

Use Model::where('user_id', $user_id)->latest()->get()->first(); it will return only one record, if not find, it will return null . Hope this will help.

What is orderby in laravel?

The Laravel Orderby works by simply sorting the results of the query. So if the column has a list of 20 data, it can sort the list by the parameter provided. One can also create an order in an ascending or a Descending Order. By Ascending Order: $users = DB::table('users')->orderBy('name', 'asc')->get();

What is default order in laravel?

Sorting is ascending by default and can be reversed by adding a hyphen ( - ) to the start of the property name.


1 Answers

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
like image 127
Tim Groeneveld Avatar answered Sep 17 '22 15:09

Tim Groeneveld