
本文介绍如何改造 laravel 表单,使其支持动态添加多组字段并一次性提交至数据库,避免重复插入或路由错误,核心在于使用嵌套数组命名字段 + 控制器循环创建模型实例。
本文介绍如何改造 laravel 表单,使其支持动态添加多组字段并一次性提交至数据库,避免重复插入或路由错误,核心在于使用嵌套数组命名字段 + 控制器循环创建模型实例。
在 Laravel 中实现“一次提交多行数据”,关键在于让表单字段具备可区分的结构化命名,而非多个同名字段(如 name="item")——后者会导致后端仅接收到最后一个值。正确做法是将每组输入封装为关联数组,例如 name="inventory[0][item]"、name="inventory[1][tax]",从而在控制器中通过 $request->inventory 获取一个二维数组,再逐条写入数据库。
以下是一个完整、健壮的实现方案:
✅ 前端:结构化表单 + 动态增删逻辑
推荐使用 ? 提示:使用 首先修正路由定义(修复拼写并推荐 RESTful 命名): 面向 CRM 系统的 MySQL 8 数据库模式设计。当用户需要为客户关系管理(CRM)系统设计、评审、优化或生成数据库模式时,应使用此项技能。 控制器中需做三件事:验证、遍历、创建。强烈建议对每行数据单独验证,防止脏数据入库: ⚠️ 重要注意事项: 通过以上改造,你将获得一个安全、可维护、符合 Laravel 最佳实践的多行表单提交方案——既解决了原始 或语义化
cloneNode)。注意修正路由名称拼写(原文 invetory 应为 inventory),并确保 CSRF 保护启用:@@######@@
@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><input type="number" step="0.01" name="inventory[${rowCounter}][tax]" class="form-control">
<td><input type="number" step="0.01" name="inventory[${rowCounter}][price]" class="form-control">
<td><input type="number" step="0.01" name="inventory[${rowCounter}][selling_price]" class="form-control">
<td><input type="number" step="0.01" name="inventory[${rowCounter}][total_price]" class="form-control">
<td><button type="button" class="btn btn-sm btn-danger remove-row">删除
`;
$('#inventoryTable tbody').append(newRow);
rowCounter++;
});
$(document).on('click', '.remove-row', function() {
$(this).closest('tr').remove();
});
</script>
@endpush@push('scripts') 确保脚本在页面底部加载,避免 DOM 未就绪报错;step="0.01" 提升数字输入体验;required 保证必填校验。✅ 后端:批量验证与安全入库
// routes/web.php
Route::post('/inventory', [InventoryController::class, 'store'])->name('inventory.store');
$request->all() —— 易受 mass assignment 漏洞影响。务必显式验证或使用 $fillable 白名单。$timestamps = true),Laravel 会自动填充 created_at/updated_at,无需手动传入。Inventory::insert() 批量插入,但需自行处理时间戳和类型转换。✅ 进阶建议
disabled + spinner);cloneNode 导致的字段覆盖问题,又规避了硬编码 SQL 或低效多次请求的缺陷。
// 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']) . ' 条记录!');
}










