so here is my problem,
for a school project i have to make a quiz website in which a normal user should be able to play a quiz, so i have to show all the questions associated to the quiz and all the answers associated to the question, but when i try to do so it only shows the answers that are associated to the final question. here is my code:
// select the clicked quiz.
$quiz = Quiz::find($id);
// get all the question and answer records from db that are associated to the selected quiz.
$questions = DB::table('questions')->where('quiz_id', $id)->get();
foreach($questions as $question)
{
$answers = DB::table('answers')->where('question_id', $question->id)->get();
}
return View::make("quizzes.makeQuiz", [
"quiz" => Quiz::find($id)
])->with('quiz', $quiz)->with('questions', $questions)->with('answers', $answers);
and here is the html (using blade):
<h3>{{ $quiz->name }}</h3><br/>
@foreach($questions as $question)
<h4>{{ $question->question }}</h4>
@foreach($answers as $answer)
<p>{{ $answer->answer }}</p>
@endforeach
@endforeach
when i try to do this without a foreach i get an error that says 'Trying to get property of non-object'. i know why i get that error because obviously $questions isn't an object.
help is very much appreciated! thanks for reading!
edit*
alright so i have now changed my code to look like this:
$questions = Question::where('quiz_id', $id)->get();
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.makeQuiz", $data);
the html is basically the same, it returns the quiz and all the questions associated. but unfortunately it only returns the answers associated to the final questions while each questions has 3 answers. i think the problem lies in $answers but i don't know exactly what i am doing wrong here :( please help! thanks!
*edit
I asked this question a second time and it solved my problem, here is the link: retrieving multiple records associated to multiple records laravel 4.2