Reputation: 23
I am doing question and answer form. I have 2 tables questions
table and choices
table. I am perfectly saving the question data and choices data to their table except the question_id
in choices table. I want to save the question id to choices table field name question_id
.
question table
| id | question |
| 1 | data1 |
| 2 | data2 |
choices table
| id | question_id | choices |
| 1 | | data1 |
| 2 | | data2 |
Below is my controller
$questions = $request->question;
foreach($questions as $question => $question_value) {
$questionsS[] = Question::create([
'question' => $request->question[$question],
]);
}
$choices = $request->choices;
foreach ($choices as $choice => $choice_value) {
$choicesS[] = Choice::create([
'question_id' => $question->id,
'choice' => $choice_value,
]);
}
I have error "Attempt to read property "id" on int" highlighting the 'question_id' => $question->id,
Hope someone help.
Upvotes: 0
Views: 40
Reputation: 1
simplely,
i dont know your goal, but if i fix it, your code should be like:
$questions = $request->question;
// may be ['question one ?', 'question two ?' ...]
$choices = $request->choices;
// may be ['choose A', 'choose B' ...]
// $questions array and $choices array must be same length
// i think in your case it will be same length, right ?
foreach($questions as $questionIndex => $question) {
$currentQuestion = Question::create([
'question' => $question,
]);
$questionsS[] = $currentQuestion;
$choicesS[] = Choice::create([
'question_id' => $currentQuestion->id,
'choice' => $choices[$questionIndex],
]);
}
$currentQuestion in loop will be an object which created from array's element, you can get id from it to create an new Choice object.
Upvotes: 0