I'm trying to update quiz but i don't know how to catch questions ids. But just for now i'm getting General error: 1366 Incorrect integer value: '["1","1","1"]' for column 'correct' and it's changing quiz name section and second question i can't catch question ids...
public function update(Request $r)
{
// quiz
$quizId = $r->get('quizId');
$name = $r->get('name');
$section = $r->get('sectionId');
// questions
$questionId = $r->get('questionId');
$question = $r->get('question');
// answers
$answerId = $r->get('answerId');
$answer = $r->get('answer');
$correct = $r->get('correct');
CourseQuiz::where('id', $quizId)->update([
'name' => $name,
'section_id' => $section
]);
foreach ($question as $q) {
CourseQuestion::where('id', $questionId)->update([
'question' => $q,
]);
}
foreach ($answer as $a) {
CourseAnswer::where('id', $answerId)->update([
'answer' => $a,
'correct' => $correct
]);
}
return redirect()->back();
}
blade
@foreach($q->questions as $qu)
<div >
<input hidden type="text" name="questionId" value="{{ $qu->id }}">
question: <input type="text" name="question[]" value="{{ $qu->question }}">
</div>
@foreach($qu->answers as $a)
<input hidden type="text" name="answerId" value="{{ $a->id }}">
<input type="checkbox" value="{{ $a->correct }}" name="correct[]" @if($a->correct !== 0) checked @else @endif>
answer: <input type="text" name="answer[]" value="{{ $a->answer }}">
@endforeach
@endforeach
CodePudding user response:
You could add the id of the question/answer as a key in the name attribute of the inputs.
@foreach($q->questions as $qu)
<div >
question: <input type="text" name="q[{{ $qu->id }}][question]" value="{{ $qu->question }}">
</div>
@foreach($qu->answers as $a)
<input type="checkbox" name="a[{{ $a->id }}][correct]" value="{{ $a->correct }}" checked' : '"' }}>
answer: <input type="text" name="a[{{ $a->id }}][answer]" value="{{ $a->answer }}">
@endforeach
@endforeach
This would group the inputs a little bit.
q[1][question]
a[1][correct]
a[1][answer]
a[2][correct]
a[2][answer]
a[3][correct]
a[3][answer]
a[4][correct]
a[4][answer]
a[5][correct]
a[5][answer]
q[2][question]
...
foreach ($r->q as $key => $value) {
CourseQuestion::where('id', $key)->update([
'question' => $value['question'],
]);
}
foreach ($r->a as $key => $value) {
CourseAnswer::where('id', $key)->update([
'answer' => $value['answer'],
'correct' => $value['correct']
]);
}
CodePudding user response:
You can debug your code with dd() helper function. I recommend you to check if $question and $answer variables are not empty inside update method.
