Laravel put array into selectbox

荒凉一梦 提交于 2019-12-06 01:55:23

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);

Use it this way:

$categories = Category::lists('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

What you need to do is instead of using the with() function with the view put inside the controller function.

$categories = Category::all();

After this you need properly reconstruct the array:

$category = array();
foreach($categories as $cat)
{
  $category[]['id'] = $cat->attributes['id'];
  $category[]['name'] = $cat->attributes['name'];
}

now in the View::make()

return View::make("stories.add",array('title'=> "Indsend novelle","categories", $category));

I hope this can be of some help.

Nat Naydenova

I like the approach suggested by Israel Ortuño

I would only add a small modification, so that the select starts with an empty "Choose from the List" option by default.

$categories = array(0=>'Choose from the list') + Category::lists('name', 'id');

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


Now the dropdown looks like this:

<option value="0">Choose from the list</option>
<option value="{whatever-the-category-id}">Category 1</option>
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!