
本文介绍如何改造 laravel 表单,使其支持动态添加多组字段并一次性提交至数据库,避免重复插入或路由错误,核心在于使用嵌套数组命名字段 + 控制器循环创建模型实例。
本文介绍如何改造 laravel 表单,使其支持动态添加多组字段并一次性提交至数据库,避免重复插入或路由错误,核心在于使用嵌套数组命名字段 + 控制器循环创建模型实例。
在 Laravel 中实现“一次提交多行数据”,关键在于让表单字段具备可区分的结构化命名,而非多个同名字段(如 name="item")——后者会导致后端仅接收到最后一个值。正确做法是将每组输入封装为关联数组,例如 name="inventory[0][item]"、name="inventory[1][tax]",从而在控制器中通过 $request->inventory 获取一个二维数组,再逐条写入数据库。
面向 CRM 系统的 MySQL 8 数据库模式设计。当用户需要为客户关系管理(CRM)系统设计、评审、优化或生成数据库模式时,应使用此项技能。
以下是一个完整、健壮的实现方案:
✅ 前端:结构化表单 + 动态增删逻辑
推荐使用 <table> 或语义化 <code><div> 容器,并配合 jQuery 管理行操作(更稳定可靠,优于原生 <code>cloneNode)。注意修正路由名称拼写(原文 invetory 应为 inventory),并确保 CSRF 保护启用:
<form action="{{ route('inventory.store') }}" method="POST">
@csrf
<div class="table-responsive">
<table class="table table-bordered" id="inventoryTable">
<thead>
<tr>
<th>商品名称</th>
<th>税率</th>
<th>成本价</th>
<th>售价</th>
<th>总价</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="inventory[0][item]" class="form-control" required></td>
<td><input type="number" step="0.01" name="inventory[0][tax]" class="form-control"></td>
<td><input type="number" step="0.01" name="inventory[0][price]" class="form-control"></td>
<td><input type="number" step="0.01" name="inventory[0][selling_price]" class="form-control"></td>
<td><input type="number" step="0.01" name="inventory[0][total_price]" class="form-control"></td>
<td><button type="button" class="btn btn-sm btn-danger remove-row">删除</button></td>
</tr>
</tbody>
</table>
</div>
<button type="button" id="addRow" class="btn btn-primary mb-2">+ 添加一行</button>
<button type="submit" class="btn btn-success">保存全部</button>
</form>
@push('scripts')
<script>
let rowCounter = 1;
$('#addRow').on('click', function() {
const newRow = `
<tr>
<td><input type="text" name="inventory[${rowCounter}][item]" class="form-control" required></td>
<td><input type="number" step="0.01" name="inventory[${rowCounter}][tax]" class="form-control"></td>
<td><input type="number" step="0.01" name="inventory[${rowCounter}][price]" class="form-control"></td>
<td><input type="number" step="0.01" name="inventory[${rowCounter}][selling_price]" class="form-control"></td>
<td><input type="number" step="0.01" name="inventory[${rowCounter}][total_price]" class="form-control"></td>
<td><button type="button" class="btn btn-sm btn-danger remove-row">删除</button></td>
</tr>
`;
$('#inventoryTable tbody').append(newRow);
rowCounter++;
});
$(document).on('click', '.remove-row', function() {
$(this).closest('tr').remove();
});
</script>
@endpush? 提示:使用
@push('scripts')确保脚本在页面底部加载,避免 DOM 未就绪报错;step="0.01"提升数字输入体验;required保证必填校验。
✅ 后端:批量验证与安全入库
首先修正路由定义(修复拼写并推荐 RESTful 命名):
// routes/web.php
Route::post('/inventory', [InventoryController::class, 'store'])->name('inventory.store');控制器中需做三件事:验证、遍历、创建。强烈建议对每行数据单独验证,防止脏数据入库:
// app/Http/Controllers/InventoryController.php
use Illuminate\Http\Request;
use App\Models\Inventory;
public function store(Request $request)
{
// 验证整个 inventory 数组(每行独立校验)
$validated = $request->validate([
'inventory.*.item' => 'required|string|max:255',
'inventory.*.tax' => 'nullable|numeric|min:0|max:100',
'inventory.*.price' => 'required|numeric|min:0',
'inventory.*.selling_price' => 'required|numeric|min:0',
'inventory.*.total_price' => 'required|numeric|min:0',
]);
// 批量创建(自动过滤空行,增强鲁棒性)
foreach ($validated['inventory'] as $data) {
// 可选:跳过完全为空的行(如用户只添加了空行未填写)
if (collect($data)->filter()->isNotEmpty()) {
Inventory::create($data);
}
}
return redirect()->route('inventory.index')->with('success', '成功添加 ' . count($validated['inventory']) . ' 条记录!');
}⚠️ 重要注意事项:
- 永远不要直接使用
$request->all()—— 易受 mass assignment 漏洞影响。务必显式验证或使用$fillable白名单。- 若模型含时间戳(
$timestamps = true),Laravel 会自动填充created_at/updated_at,无需手动传入。- 如需更高性能(大量数据),可改用
Inventory::insert()批量插入,但需自行处理时间戳和类型转换。
✅ 进阶建议
-
前端防误提交:添加提交按钮禁用 + Loading 状态(如
disabled+ spinner); - 服务端幂等性:对关键业务场景(如库存扣减),建议引入唯一请求 ID 或事务锁;
- 用户体验优化:添加行号、键盘快捷键(Enter 新增、Delete 删除)、实时总价计算等。
通过以上改造,你将获得一个安全、可维护、符合 Laravel 最佳实践的多行表单提交方案——既解决了原始 cloneNode 导致的字段覆盖问题,又规避了硬编码 SQL 或低效多次请求的缺陷。

















