skip to Main Content

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


  1. 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:

    public function questionDashboard() {
        $questions = Question::with('answers')->get();
        return view('admin.questionDashboard', ['questions' => $questions]);
    }
    

    Then make sure the Question and Answer models are set up with the proper relationships.

    Question Model:

    public function answers()
    {
        return $this->hasMany(Answer::class, 'id_question');
    }
    

    Answer Model:

    public function question()
    {
        return $this->belongsTo(Question::class, 'id_question');
    }
    

    Blade view:
    You can loop through each question and its related answers like this:

    @foreach ($questions as $question)
        <h3>{{ $question->question }}</h3>
        <ul>
            @foreach ($question->answers as $answer)
                <li>{{ $answer->answer }}</li>
            @endforeach
        </ul>
    @endforeach
    
    Login or Signup to reply.
  2. Just use relationships to make it easy.

    public function question_dashboard(){
         $questions = Question::with('answers')->get();
         return view('admin.question.dashboard', (['questions'=>$questions]));
    }
    

    Question Model:

    public function answers()
    {
        return $this->hasMany(Answer::class, 'id_question');
    }
    

    Answer Model

    public function question()
    {
        return $this->belongsTo(Question::class);
    }
    

    Note:
    Use related name for the column name like id_question => question_id.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search