Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel eloquent lists - Sorting A List Of Column Values

Using laravel and I'm creating a select box on a form. I've been using the helper to create the select box and all is working fine.

I retrieve the data for the select box from a database and use the following to retrieve the data:

$data = model::lists('name','id')

Again all works ok and this returns the expected array

My problem though is I can't seem to sort this list - i've tried adding orderBy() but no joy.

Other than using a native php function is there a laravel method to sort a list?

like image 975
Ray Avatar asked Jul 12 '13 05:07

Ray


2 Answers

You can put whatever you want, and then list it. I mean:

model::orderBy('orderByColumn')->lists('name', 'id');

As long as lists is the last method in the chain, other methods works just fine.


Starting from Laravel version 5.3 lists is going to be deprecated, use pluck instead:

model::orderBy('orderByColumn')->pluck('name', 'id');
like image 75
Umut Sirin Avatar answered Oct 18 '22 22:10

Umut Sirin


You can try:

$data = model::select('name','id')->orderBy('name');

If that doesn't work, toss a ->get() on the end:

$data = model::select('name','id')->orderBy('name')->get();
like image 4
thestepafter Avatar answered Oct 19 '22 00:10

thestepafter