You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel实现表单多行数据批量提交至MySQL的问题

问题解决:Laravel动态表单行批量提交到MySQL

核心问题分析

当前代码无法批量提交的原因是:所有输入框的name属性为单个值(如item),复制多行后提交时,同名字段会被覆盖,后端仅能接收最后一行数据。需将输入框的name改为数组格式,让后端能接收多行数据集合。

步骤1:修改表单输入框的name属性

把每个输入框的name改为数组形式(如item[]),提交时会自动将所有行的对应字段打包成数组传递给后端:

<form action="{{route('invetory.create')}}" method="post">
    @csrf
    <div class="service-row"> <!-- 将id改为class,避免复制后id重复冲突 -->
        <input type="text" name="item[]"/>
        <input type="text" name="tax[]" />
        <input name="price[]" type="text" />
        <input name="selling_price[]" type="text" />
        <input name="total_price[]" type="text" />
    </div>
    <input type="submit" value="提交"/> <!-- 把提交按钮移到表单底部,避免每行都生成提交按钮 -->
</form>   
<a class="btn-floating btn-primary" id="addmore" onclick="duplicate()">Add More</a>

步骤2:调整复制脚本逻辑

修改JS代码,复制带class的行并清空新行输入框内容,避免复制原数据:

function duplicate() {    
    var original = document.querySelector('.service-row');
    var clone = original.cloneNode(true); // 深度复制行内所有元素
    // 清空复制后的输入框内容
    clone.querySelectorAll('input').forEach(input => input.value = '');
    // 将新行插入到原行的后方
    original.parentNode.appendChild(clone);
}

步骤3:修改控制器实现批量保存

后端接收数组格式的参数后,循环遍历每行数据,逐个创建Inventory记录:

public function create(Request $request){
    // 可选:添加数据验证,确保提交的每行数据合法
    $request->validate([
        'item.*' => 'required|string',
        'tax.*' => 'required|numeric',
        'price.*' => 'required|numeric',
        'selling_price.*' => 'required|numeric',
        'total_price.*' => 'required|numeric',
    ]);

    // 遍历数组,批量创建数据库记录
    foreach($request->item as $index => $item){
        Inventory::create([
            'item' => $item,
            'tax' => $request->tax[$index],
            'price' => $request->price[$index],
            'selling_price' => $request->selling_price[$index],
            'total_price' => $request->total_price[$index],
        ]);
    }

    return redirect()->action([InventoryController::class, 'index']);
}

注意:需确保Inventory模型中配置了$fillable属性,允许批量赋值:

// app/Models/Inventory.php
protected $fillable = ['item', 'tax', 'price', 'selling_price', 'total_price'];

额外优化建议

  • 添加删除行功能:给每行新增删除按钮,点击时移除当前行;
  • 前端实时计算:根据price和tax自动计算total_price,提升用户体验;
  • 事务包裹批量操作:确保所有行数据要么全部保存成功,要么全部回滚,保证数据一致性:
    DB::transaction(function() use ($request){
        foreach($request->item as $index => $item){
            Inventory::create([...]);
        }
    });
    

内容的提问来源于stack exchange,提问作者vivek kn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:20:31