我在for循环中输入了一个增量:
<input type="number" name="device_id_1">
<input type="number" name="device_id_2">
...
<input type="number" name="name_1">
<input type="number" name="name_2">
我使用ajax将数据传递给控制器:
dd( $request->all());
//dd will return the data like:
"device_id_1" => "100"
"name_1" => "Some Name"
"device_id_2" => "200"
"name_2" => "Other type"
....
我在保存每个 device_id_X 以及其余的问题时遇到了问题,我该如何在 foreach 循环中保存数据?
我当前的foreach循环当然不起作用:
foreach ($devices as $index => $deviceId) {
$devicesS[] = Device::create([
'device_id' => $deviceId,
'name' => $request->name_[$index],
.....
]);
}
答案 0 :(得分:0)
您可能会:
<input type="hidden" name="items[]">
<input type="number" name="device_id_1">
<input type="number" name="name_1">
...
<input type="hidden" name="items[]">
<input type="number" name="device_id_2">
<input type="number" name="name_2">
这将导致以下结果:
foreach ($request->items as $index => $item) {
$devices[] = [
'device_id' => $request->get('device_id_'. $index + 1),
'name' => $request->get('name_'. $index + 1)
];
}
Device::insert($devices);