Emma
Emma

Reputation: 13

Laravel-Displaying one to many relationship in view

I am currently adding a feature to my website that asks questions and gives multiple choice answers.

My Answer Model has code like:

protected $table = 'answer';
protected $primaryKey = 'answer_id';
protected $fillable = ['question_id'];


 public function question()
{
    return $this->belongsTo('App\Question','question_id')->distinct();
}

and my view is like:

@foreach ($answers as $answer)



<h2>{{$answer->question->question}}</h2>

  <p>{{$answer->answer}}</p>

@endforeach

My controller is:

     $answers = Answer::with('question')->first()->get();

It is displaying like:

question1

answer here

question1

answer here 2

question1

answer here 3

question2

2 answer here

question2

2 answer here 2

question2

2 answer here 3

I want to only show the question once. I am new to Laravel.

Upvotes: 1

Views: 3542

Answers (1)

jszobody
jszobody

Reputation: 28911

You need to flip this then, and first get your questions from the DB:

$questions = Question::with('answers')->get();

This of course assumes you've already setup a hasMany relationship in your Question model.

Then in your view you'll have two loops:

@foreach ($questions as $question)
    <h2>{{$question->question}}</h2>

    @foreach ($question->answers as $answer)     
        <p>{{$answer->answer}}</p>
    @endforeach

@endforeach

Note how you first loop through questions and display the question once, then loop through the answers for each question.

Upvotes: 3

Related Questions