recently i asked this question which got one answer but unfortunately didn't solve the problem, after that i got no more answers and i really need to fix this problem i have.
Alright so i have to make a quiz website for my school in which a user should be able to play the quiz, this page need to show the quiz name, the questions associated to the quiz and the answers associated to the questions. I can show the quiz name no problem and i can show the questions aswell, but for some reason only the answers associated to the final question are shown.
Here's my code:
public function playQuiz($id)
{
// get all the questions associated to the selected quiz
$questions = Question::where('quiz_id', $id)->get();
// get all the answers associated to the questions
foreach($questions as $question)
{
$answers = Answer::where('question_id', $question->id)->get();
}
$data = [
'quiz' => Quiz::find($id),
'questions' => $questions,
'answers' => $answers
];
return View::make("quizzes.playQuiz", $data);
}
The $id variable is the id of the quiz i selected so i should be able to retrieve all data associated to this id, and all data associated to the associated data of this id.
Here's my html (with blade):
<h3>{{ $quiz->name }}</h3>
@foreach($questions as $question)
<h4>{{ $question->question }}</h4>
@foreach($answers as $answer)
@if($answer->question_id == $question->id)
<p>{{ $answer->answer }}</p>
@endif
@endforeach
@endforeach
I know that the problem lies within the way i get my answers from the db but i don't know how to fix it. Help is much appreciated! Thanks for reading!
*edit,
my db scheme goes as follows:
i have
- a table called quizzes with an id, name and description.
- a table called questions with an id, question and a foreign key "quiz_id"
- a table called answers with an id, answer and a foreign key "question_id"
a quiz can have multiple questions but a question can only have one quiz, a question can have multiple answers but an answer can only have one question.
i hope that is enough information about my database, thanks for helping out!