0

I have a list of items in database table of a structure: id, name.

I need to populate a select box with items sorted by their names along with "All" element with an id = 0 as the first one. What is wrong is that the element doesn't appear in a list box at all.

Controller method:

public function getItems(){

$items = Item::orderBy('name', 'ASC')->lists('name', 'id');
$items_all = array(0 => 'All');
array_merge($items_all, $items);
return View::make('items')->with('items', $items);
}

and a view:

{{ Form::select('item_id', $items, Input::Get('item_id'), array('class'=>'form-control')) }}

2 Answers 2

1

array_merge returns the new array, so you have to assign the return value to $items:

$items = array_merge($items_all, $items);

Or you can bring it down to this syntax if you want to:

$items = array_merge(['0' => 'All'], $items);

To preseve the order of your array items you can use this:

$items = $items_all + $items;
Sign up to request clarification or add additional context in comments.

5 Comments

That's was my mistake. I was doing that before, but I'm getting completely unsorted list now..?
What does unsorted mean? can you add a var_dump of $items before and after array_merge to your question?
Unsorted by name. They have renumbered by id
How about $items = ['0' => 'All'] + $items; instead of array_merge?
Instead of using array_merge, I need to use $items = $items_all + $items; That solves all my problems here
0

After updating

array_merge($items_all, $items)

to

$items = array_merge($items_all, $items)

all select box elements got displayed, including 'All', but array_merge renumbers elements, so I used:

$items = $items_all + $items;

as @lukasgeiter suggested at the same time, so I chose his answer as final.

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.