lundi 7 mars 2016

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire