dongrong6235 2018-02-16 14:01
浏览 127
已采纳

多个选择字段 - 选择字段必须是一个数组,$ request输出中只显示一个<option>

I have the code below that is a resume of the process to create a new conference. To create a new conference is ncessary that the user introduce some info like the conference name, etc. The user also needs to introduce between 1 and 3 categories for the conference.

So there is a select element using select2 plugin so the user can select the categories:

<div class="form-row">
    <div class="form-group col-lg-6">
        <label for="categories">Category</label>
        <select id="tag_list" required  multiple class="form-control" value="{{ old('categories') }}" name="categories" id="categories">
            @foreach($categories as $category)
                <option value="{{$category->id}}">{{$category->name}}</option>
            @endforeach
        </select>
    </div>
</div>

Then the laravel code to store the conference info and also the categories of the conference in the conference_category table since there is a many to many relationship between confernece and category:

public function store(Request $request)
    {
        $this->validate($request, [
            'conference_name' => 'required|max:255|string',
            'conference_categories' => 'required|array|between:1,3|integer',
        ]);

        $conference = Conference::create([
            'name' => $request->conference_name,
        ]);

        $conference->categories()->attach($request->conference_categories);
    }

The select2 JS:

$(function() {
    $('#tag_list').select2({
        placeholder: '',
        dropdownAutoWidth: 'true',
        width: '100%'
    });
});

Errors

  • If the user selects more than one category in the $request output just appears the id of one category
  • And it appears a laravel validation error after submit the form "The conference categories must be an array. "

Do you know where can be the issue?

  • 写回答

1条回答 默认 最新

  • donglian1384 2018-02-16 14:19
    关注

    You gotta change the name attribute of your select to an array, like this and also remove one id attribute from it, it can't have 2

    <select required  multiple class="form-control" value="{{ old('categories') }}" name="categories[]" id="categories">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解