Laravel put array into selectbox

kim larsen picture kim larsen · Jun 18, 2013 · Viewed 16.5k times · Source

I am facing some problems with my selectbox, where i will put all available categories into the

In my controller i am using this snip:

 return View::make("stories.add")
        ->with("title","Indsend novelle")
        ->with("categories", Category::all());

In my view i am trying to put all categories into the selectbox with this:

 {{Form::select("category", $categories)}}

I could make this, but that won't work, because Form::select has to be as an array?

@foreach ( $categories as $category )
    {{$category->name}}
@endforeach

What to do?

I have made this and it works, but it looks too ugly and not user-friendly, any suggestions?

  $test = Category::all(); $myArray = array();
    foreach ( $test as $o):
          $myArray[] = $o->name;
    endforeach;

    return View::make("stories.add")
        ->with("title","Indsend novelle")
        ->with("categories", $myArray);

var_dump:

    array(2) {
      [0]=>
      object(Category)#36 (5) {
        ["attributes"]=>
array(4) {
  ["id"]=>
  string(1) "1"
  ["name"]=>
  string(12) "Alderforskel"
  ["created_at"]=>
  string(19) "0000-00-00 00:00:00"
  ["updated_at"]=>
  string(19) "0000-00-00 00:00:00"
}
["original"]=>
array(4) {
  ["id"]=>
  string(1) "1"
  ["name"]=>
  string(12) "Alderforskel"
  ["created_at"]=>
  string(19) "0000-00-00 00:00:00"
  ["updated_at"]=>
  string(19) "0000-00-00 00:00:00"
}
["relationships"]=>
array(0) {
}
["exists"]=>
bool(true)
["includes"]=>
array(0) {
}
}
       [1]=>
   object(Category)#39 (5) {
  ["attributes"]=>
  array(4) {
  ["id"]=>
  string(1) "2"
  ["name"]=>
  string(7) "Bondage"
  ["created_at"]=>
  string(19) "0000-00-00 00:00:00"
  ["updated_at"]=>
  string(19) "0000-00-00 00:00:00"
}
["original"]=>
 array(4) {
  ["id"]=>
  string(1) "2"
  ["name"]=>
  string(7) "Bondage"
  ["created_at"]=>
  string(19) "0000-00-00 00:00:00"
  ["updated_at"]=>
  string(19) "0000-00-00 00:00:00"
}
["relationships"]=>
array(0) {
}
["exists"]=>
bool(true)
["includes"]=>
array(0) {
}
}
}

Answer

Israel Ortuño picture Israel Ortuño · Jun 18, 2013

Use it this way:

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

return View::make('....', compact('categories'));

And now in the view:

{{ Form::select('selectName', $categories, null); }}

Edit: Found in the docs Query builder # Select Have a look to this