Reputation: 31
i want to create multi record with createMany , how can i insert array to this method Without Data replication ?
public function update(Request $request, Question $question)
{
$options = $request->only('title', 'description', 'question_id');
$options_data = [];
foreach ($options as $key => $value) {
$options_data[] =[
'title' => $options[$key],
'description' =>$options[$key],
'question_id' => $options[$key]
];
}
$question->options()->createMany($options_data);
result: dd() i submit 2 record with 3 fields
array:3 [▼
0 => array:3 [▼
"title" => array:2 [▼
0 => "option one"
1 => "option two"
]
"description" => array:2 [▼
0 => "option one"
1 => "option two"
]
"question_id" => array:2 [▼
0 => "option one"
1 => "option two"
]
]
1 => array:3 [▼
"title" => array:2 [▼
0 => "option description"
1 => "option two description"
]
"description" => array:2 [▼
0 => "option description"
1 => "option two description"
]
"question_id" => array:2 [▼
0 => "option description"
1 => "option two description"
]
]
2 => array:3 [▼
"title" => array:2 [▼
0 => "14"
1 => "14"
]
"description" => array:2 [▼
0 => "14"
1 => "14"
]
"question_id" => array:2 [▼
0 => "14"
1 => "14"
]
]
]
My form have 3 fields for submit to this model title[],description[],question_id[] this form is a repeatable form
Upvotes: 3
Views: 30163
Reputation: 56
From what I see you didn't form the html file correctly. Your html file should look like this
<input type="text" name="items[1][title]">
<input type="text" name="items[1][description]">
<input type="text" name="items[1][question_id]">
<input type="text" name="items[2][title]">
<input type="text" name="items[2][description]">
<input type="text" name="items[2][question_id]">
$options = $request->only('items');
$options_data = [];
foreach ($options as $key => $value) {
$options_data[] = $value;
}
$question->options()->createMany($options_data);
Upvotes: 4