If the user is doing a registraiton in a conference and the registration form colllect this data:
"name" => array:1 [▼
1 => array:2 [▼
1 => "Jake" // name of the participant being registered in the registration_type_id 1
2 => "John" // name of the participant being registered in the registration_type_id 1
]
]
"surname" => array:1 [▼
1 => array:2 [▼
1 => "W" // surname off 1st participant being registered in the registration_type_id 1
2 => "K" // surname off 2nd participant being registered in the registration_type_id 1
]
]
"answer" => array:1 [▼
1 => array:2 [▼
1 => array:2 [▼ // answers of the 1st participant being registered in the registration_type_id 1
1 => "answer1p1"
2 => "answer2p1"
]
2 => array:2 [▼ // answers of 2nd participant being registered in the registration_type_id 1
1 => "answer1p2"
2 => "answer2p2"
]
]
]
Then is necessary to store the participants info the in the participants table and the answers associated with each participant in the answers table. Insert in participants table is working fine.
Issue: To insert in the answers table is not working properly. In the database it should be stored like:
id | participant_id | question_id | answer
159 | 153 | 1 | answer1p1
161 | 153 | 2 | answer2p1
163 | 154 | 1 | answer1p2
165 | 154 | 2 | answer2p2
But is stored like this:
id | participant_id | question_id | answer
159 | 153 | 1 | answer1p1
161 | 153 | 1 | answer1p2
163 | 154 | 1 | answer1p1
165 | 154 | 1 | answer1p2
160 | 153 | 2 | answer2p1
162 | 153 | 2 | answer2p2
164 | 154 | 2 | answer2p1
166 | 154 | 2 | answer2p2
code to insert in participants and answers table:
foreach ($request->all()['name'] as $key => $nameArray) {
foreach ($nameArray as $nameKey => $name) {
$participant_result = Participant::create([
'name' => $name,
'surname' => $request['surname'][$key][$nameKey],
'registration_id' => $registration->id,
'registration_type_id' => $key
]);
if(isset($request['answer'][$key])) {
foreach ($request->all()['answer'][$key] as $rID => $answers) {
foreach ($answers as $question_id => $answer) {
$answer = Answer::create([
'question_id' => $question_id,
'participant_id' => $participant_result->id,
'answer' => $answer,
]);
}
}
}
}
}
Like this:
foreach ($request->all()['name'] as $key => $nameArray) {
foreach ($nameArray as $nameKey => $name) {
$participant_result = Participant::create([
'name' => $name,
'surname' => $request['surname'][$key][$nameKey],
'registration_id' => $registration->id,
'registration_type_id' => $key
]);
}
}
if(isset($request['answer'][$key])) {
foreach ($request->all()['answer'][$key] as $rID => $answers) {
foreach ($answers as $question_id => $answer) {
$answer = Answer::create([
'question_id' => $question_id,
'participant_id' => $participant_result->id,
'answer' => $answer,
]);
}
}
}
Inserts differently but also incorrectly:
id | participant_id | question_id | answer
167 | 156 1 answer1p1
169 | 156 1 answer1p2
168 | 156 2 answer2p1
170 | 156 2 answer2p2