代码之家  ›  专栏  ›  技术社区  ›  archvist

如何在foreach语句中包含多个输入

  •  1
  • archvist  · 技术社区  · 8 年前

    我有两个输入字段,用户可以重复这些字段,以便在一个表单提交中插入多个记录。我目前正在使用foreach循环来循环其中一个输入并获取值,但是现在我需要同时循环两个输入以将数据保存在一起。

    我想通过 input-type & input-label 并将存储的值保存到数据库中。

    我想我可以创建两个foreach循环,但这似乎是一种可怕的方式。

    表格-

    <form method="post" action="{{ route('savePage') }}">
        {{ csrf_field() }}
        <ul class="field-list">
            <li v-for="(input, index) in inputs">
                <input type="text" name="input-type[]" v-model="input.one" style="display: none">
                <input type="text" name="input-label[]" v-model="input.two" placeholder="Label name">
                <p><span class="codesnippet">text</span></p>
                <button class="p-btn secondary" @click.prevent="deleteRow(index)" >Remove field</button>
            </li>
        </ul>
        <button>Submit</button>
    </form>
    

    控制器-

    public function saveAtt(Request $request)
    {
        foreach ($request->input('input-label') as $label) {
    
            $field = new Attribute;
            $field->page_id = 1;
            $field->label = $label;
            $field->type = 2;
            $field->save();
        }
    
        return redirect()->route('indexPage');
    }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Jonas Staudenmeir    8 年前

    使用此选项:

    $types = $request->input('input-type');
    foreach ($request->input('input-label') as $i => $label) {
        $field = new Attribute;
        $field->page_id = 1;
        $field->label = $label;
        $field->type = $types[$i];
        $field->save();
    }
    
    推荐文章