31

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?

1
  • Great question. Normally need to put where's, etc on the query to create an array to populate a select with Laravel. Commented Feb 8, 2015 at 5:22

3 Answers 3

70

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');
Sign up to request clarification or add additional context in comments.

8 Comments

You could also use php array sorting once you get the array PHP: Sorting arrays
excellent - thank you. I was trying to orderBy after the lists. I hadnt realised the order of these functions. Thanks again
Thank you, thank you, thank you @umut-sirin. Much love from Detroit!
When Laravel 5.3 comes our lists will be deprecated. It has been renamed to pluck. The method signature is the same. Please don't use lists anymore as you have access to pluck in current versions.
model::orderBy('orderByColumn')->pluck('name', 'id'); not valid in my case. I found this solution: model::all()->sortby('Name')->pluck('Name', 'id');
|
4

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();

1 Comment

Hi - I tried this also but struggled to implement the object in the html select helper the data was intended for. The result was correct but couldnt implement. Lists was easier as it contained the exact data I needed
0

when I

dd(YourModel::pluck('name', 'id'));

I see it is Collection Class so I found collection laravel and then I found method sortKeys() so I do:

YourModel::pluck('name', 'id')->sortKeys();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.