I usually dd at key places to see what data I have, and use the network tab also to check your response.
Meaning dd and network tab while developing.
I've been running around the circle to fix this issue.
To explain this in summary we are trying to upload a multiple files inside an array. For each questions there's choices and each choices has image attachments.
As an example I'm trying to add 2 questions with 2 choices with image attachment each. So it will be an index of 0 and 1. It is inserting data in the database but the file that is being uploaded to index 0 is the same with index 1. So in short that data in index 0 is duplicated.
Here's my code.
foreach (array_unique($types) as $type) {
if ($type == 'Multiple Choice') {
$questions = $request->get('question_c'); // assign array of questions
if ($request->hasFile('desc_url_c')) {
$image = $request->file('desc_url_c'); // assign array of images
}
// loop through the questions array
foreach($questions as $key => $val) {
$choices = new AssessmentChoice();
$choices->setConnection($this->getDb());
$choices->assessment_id = $assessment->id;
$choices->question_c = $request->question_c[$key];
$choices->points_c = $request->points_c[$key];
$choices->description_c = $request->description_c[$key];
$file = $image[$key] ?? null;
if ($file != null) {
$desc_url_c = $file->store($this->getDb().'/assessments/multiple-choice');
$choices->desc_url_c = $desc_url_c;
} else {
$choices->desc_url_c = null;
}
$choices->correct_c = $request->correct_c[$key];
$choices->type = 'Multiple Choice';
$choices->save();
if ($request->hasFile('option_url_c')) {
$images = $request->file('option_url_c'); // assign array of images
}
// decode options into array ["Option 1", "Option 2"]
$optionArr = json_decode($request->option_c[$key], true);
foreach ($optionArr as $file => $val) {
$files = $images[$file] ?? null;
$choiceFiles = new AssessmentChoiceFile();
$choiceFiles->setConnection($this->getDb());
$choiceFiles->assessment_id = $assessment->id;
$choiceFiles->assessment_choice_id = $choices->id;
$choiceFiles->option_c = $val;
if ($files != null) {
$choiceFile = $files->store($this->getDb().'/assessments/multiple-choice');
$choiceFiles->option_url_c = $choiceFile;
} else {
$choiceFiles->option_url_c = null;
}
$choiceFiles->save();
}
}
I'm not sure if I'm doing it correctly, not sure if I'm passing the correct for the image upload.
Please or to participate in this conversation.