7

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

Community
  • 1
  • 1
Anastasie Laurent
  • 1,169
  • 6
  • 23
  • 35
  • Please show how you get your values in $categories. It looks like you have JSON instead of an array in it. – peterm Jul 12 '14 at 00:16
  • http://stackoverflow.com/questions/29508297/laravel-5-how-to-populate-select-box-from-database-with-id-value-and-name-value/43039370#43039370 – itzmebibin Mar 27 '17 at 06:34

1 Answers1

13

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) }}
peterm
  • 91,357
  • 15
  • 148
  • 157
  • first of all thank you. second where is the official documentation for that. lastly, I got this `` I should have got this ``, how to fix that please? +1 – Anastasie Laurent Jul 12 '14 at 00:55
  • 2
    It seems that you reversed parameters in `lists()`. Take a closer look it should go `'name', 'id'` not vice versa. As far as the documentation is concerned take a look at http://laravel.com/docs/queries#selects. Specifically 'Retrieving A List Of Column Values'. – peterm Jul 12 '14 at 01:11