Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel blade how to set the options for drop down list

I am trying to create an drop down list using blade

I have already checked this question Laravel 4 blade drop-down list class attribute

I tried this:

 {{Form::select('category_id', $categories)}}

and the result is:

<select name="category_id"><option value="0">{"id":2,"name":"Apartment"}</option><option value="1">{"id":3,"name":"Car"}</option></select>

I couldn't know how to show just the name value of the options. plus I couldn't know how to set the value of each option to its id

I know the forth parameter is the option one, and I tried to do this

 {{Form::select('category_id', $categories, '', $categories)}}

but I got this exception:

htmlentities() expects parameter 1 to be string, array given (View: 

please notice that the $categories is array, each row has id and name

Update 1

I send the value from controller to view like this

 $categories = Category::All(['id', 'name']);

where Category is a model

like image 276
Anastasie Laurent Avatar asked Jul 12 '14 00:07

Anastasie Laurent


1 Answers

Form::select() requires a flat array like

array(
  1 => 'Appartment',
  2 => 'Car'
)

whereas $categories = Category::all() gives you a multidimensional array that looks like

array(
  0 => array(
    'id' => 1,
    'name' => 'Appartment'
  ),
  1 => array(
    'id' => 2,
    'name' => 'Car'
  )
)

That being said just change

$categories = Category::all(['id', 'name']);

to

$categories = Category::lists('name', 'id');

Then this will work just fine

{{ Form::select('category_id', $categories) }}
like image 122
peterm Avatar answered Oct 08 '22 12:10

peterm