Generate drop-down list input with values from DB

2020-02-28 07:41发布

I am trying to generate a drop-down list with values from a MySQL table using Laravel. The table is simple, two columns - id and category.

The following will retrieve all of the records (categories) but returns an object rather than an array, which is what I need for the drop-down code -

$categories = Category::all();

The code for the drop-down is:

{{ Form::select('category', $categories, $post->category_id) }}

Ideas?

UPDATE

bgallagh3r suggested using a foreach loop to convert each category to an array. Their code got me close but generated a bunch of funky nested optgrouptags. I was able to get it down to just one optgroup but that is one too many..

$categories = Category::all();
foreach ($categories as $cat)
{
    $category = $cat->to_array();
    $id = $category['id'];
    $value = $category['category'];
    $cats[] = array($id => $value);
}

And then, in the form:

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

I end up with this HTML:

    <select name="categories">
    <optgroup label="0">
    <option value="1">Department News</option>
    </optgroup>
    <optgroup label="1">
    <option value="2">General</option>
    </optgroup>
   ...
    </select>

标签: php laravel
7条回答
Root(大扎)
2楼-- · 2020-02-28 08:33

Depending on if you are using Eloquent for your models Category will return an array of objects, you need to convert the objects to arrays before passing them to the Form class.

foreach (Category::all() as $cat)
{
    $categories[] = array($cat->id => $cat->category);
}
{{ Form::select('categories', $categories)}}
查看更多
登录 后发表回答