laravel 5.4 select2 多项编辑

laravel 5.4 select2 multiple edit

我不知道如何填充我的 select2 表单的编辑功能。这是我的尝试。控制器:

public function edit($id)
{
    $company = Company::find($id);      

    $categories = MainCategory::all();
    $categories2 = array();
        foreach ($categories as $category) {
        $categories2[$category->main_cat_id] = $category->main_cat_name;
    }

    return view('company/edit_company')->with('company', $company)->with('categories', $categories2);
}

这是我的观点:

<select class="form-control select2-multi" name="company_main_cat[]" multiple="multiple" style="width: 50%" data-placeholder="select main category">
<option value='{{$category->main_cat_id}}'>{{$category->main_cat_name}}</option>
</select>

这是我的 JS:

<script type="text/javascript">
$('.select2-multi').select2();
$('.select2-multi').select2().val({!! json_encode($company->maincategories()->allRelatedIds()) !!}).trigger('change');
</script>

如果您将类别数据正确地显示在您的视图中;这似乎是代码中的一个数组。您可以在 select 元素中 foreach 它们。

<select class="form-control select2-multi" name="company_main_cat[]" multiple="multiple" style="width: 50%" data-placeholder="select main category">
  @foreach($category as $category_single)
    <option value='{{$category_single->main_cat_id}}'>{{$category_single->main_cat_name}}</option>
  @endforeach
</select>