如何使用Laravel插入多个文本字段数据。 我有两个领域。
<input type="text" name="title[]" />
<input type="text" name="email[]" />
现在在控制器中我可以得到如下的这些值。
$name = $request->title;
$description = $request->email;
这是我打印这些值时所得到的。
Array
(
[0] => title1
[1] => title2
)
Array
(
[0] => desc1
[1] => desc2
)
如何用雄辩的方式添加它。
答案 0 :(得分:6)
方法1:
$name = $request->title;
$description = $request->email;
if(count($name) > count($description))
$count = count($description);
else $count = count($name);
for($i = 0; $i < $count; $i++){
$objModel = new ModelName();
$objModel->name = $name[$i];
$objModel->description = $description[$i];
$objModel->save();
}
方法2:
$name = $request->title;
$description = $request->email;
if(count($name) > count($description))
$count = count($description);
else $count = count($name);
for($i = 0; $i < $count; $i++){
$data = array(
'name' => $name[$i],
'description' => $description[$i]
);
$insertData[] = $data;
}
ModelName::insert($insertData);