I can input data into 2 different tables, namely the question table and the answer table. But I have difficulty displaying the data according to each id_question. I have tried it but all the data in the answer table is displayed.
This is some example data for each Table.
question
Id | question |
---|---|
1 | The correct answer is |
2 | How old is Ani? |
answer
Id | id_question | answer |
---|---|---|
1 | 1 | give |
2 | 1 | given |
3 | 1 | gave |
4 | 1 | gain |
5 | 2 | 8 years old |
6 | 2 | 9 years old |
7 | 2 | 10 years old |
8 | 2 | 11 years old |
And this is my controller:
public function question Dashboard(){
$questions = Question::with('answers')->get();
$answers = Answer::with('questions')->get();
return view('admin.questionDashboard', ([`questions`=>$questions, `answers`=>$answers]));
}
2
Answers
There’s no need to fetch the answers separately as the
with()
method eager-loads them already. Here’s how you can adjust your controller:Updated Controller:
Then make sure the
Question
andAnswer
models are set up with the proper relationships.Question Model:
Answer Model:
Blade view:
You can loop through each question and its related answers like this:
Just use relationships to make it easy.
Question Model:
Answer Model
Note:
Use related name for the column name like id_question => question_id.