How to capture and process inputs from a dynamically generated form
Looking for some advice on how to capture and process inputs from a dynamically generated form.
Use Case:
Teacher A uploads an assignment text file with 5 questions that students must submit answers to online.
Teacher B uploads an assignment text file with 7 questions that students must submit answers to online.
Teacher C uploads an assignment text file with 8 questions that students must submit answers to online.
Teacher D uploads an assignment text file with 2 questions that students must submit answers to online.
The number of questions can vary when these teachers give another assignment the next time.
For each assignment students will see a form that has questions and a text box below each question that students must fill.
The creation of the form is probably easily as I can assign the input id by joining the word question_ and the id for the question stored in the database.
My question is - How would the input controller store these questions and answer. For example,
You can use a loop to capture the inputs from the dynamically generated form. For example, you can use a foreach loop to loop through the form inputs and store them in an array. Then you can use the array_values function to get the values from the array and store them in variables.
$inputs = $request->all();
$answers = [];
foreach ($inputs as $inputKey => $inputValue) {
if (strpos($inputKey, 'question_') !== false) {
$questionId = str_replace('question_', '', $inputKey);
$answers[$questionId] = $inputValue;
}
}
// Now you have an array of answers, you can store them in the database