Khirad Zahra
Khirad Zahra

Reputation: 893

How to insert array fields data in Laravel5

How can I insert multiple text fields data with Laravel. I have two fields.

<input type="text" name="title[]" />
<input type="text" name="email[]" />

Now in controller I can get these values as below.

$name =  $request->title;
$description =  $request->email;

Here what i get when i print these values.

Array
(
    [0] => title1
    [1] => title2
)
Array
(
    [0] => desc1
    [1] => desc2
)

How can I add this with eloquent.

Upvotes: 2

Views: 13455

Answers (1)

shafiq.rst
shafiq.rst

Reputation: 1296

Method 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();
}

Method 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);

Upvotes: 6

Related Questions