Skip to content
Advertisement

Laravel put array into selectbox

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) {
}
}
}

Advertisement

Answer

What you need to do is give Form::select() an array of category names and their ids. If you iterate over the categories, you can aggregate these and then pass them to Form::select().

$categories = Categories::all();
$selectCategories = array();

foreach($categories as $category) {
    $selectedCategories[$category->id] = $category->name;
}

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement