Hello,
I am fairly new to Laravel and have been following a bunch of tutorials. I am now trying to create a simple quiz application to learn more, but I might use some advice.
In the application it is possible to create multiple quizzes. Each quiz has multiple questions and each question has multiple answers. I've made the relations between them like so:
Quiz model
public function questions(){
return $this->hasMany(Question::class);
}
Question model
public function answers(){
return $this->hasMany(Answer::class);
}
public function quiz(){
return $this->belongsTo(Quiz::class);
}
Answer model
public function question(){
$this->belongsTo(Question::class);
}
So far it ain't that complicated and I think it's fine, but I am trying to add a extra model called Result that remembers which question the user is currently in. It should do more in the future but so far it contains a quiz_id and a question_number. I added the relation within the quiz model like so:
public function result(){
return $this->hasOne(Result::class);
}
Everytime the user opens the url quiz/ it calls a controller method:
public function show(Quiz $quiz)
{
$result = $quiz->result;
$questions = $quiz->questions->toArray();
foreach($questions as $data){
if($data['id'] == $result->question_number){
$question = Question::find($data['id']);
break;
}
}
$answers = $question->answers;
return view('website.quiz.show', compact('quiz', 'question', 'answers'));
}
This code actually works fine it shows the question with it's answers according to the question_number in Result. But I think it's not the way it should be done and it does not feel right to get all questions with a query when I only need one.
So my question is could someone push me a little more into the right direction in how I should setup the controller? Or am I doing it wrong entirely?