如何在Laravel5中插入数组字段数据

时间:2017-03-29 12:50:10

标签: laravel-5 laravel-eloquent

如何使用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
)

如何用雄辩的方式添加它。

1 个答案:

答案 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);