Search code examples
laravel-5laravel-5.3

I want to fetch an questions by id and it has multiple answers


I have Question model that has many answers

class Question extends Model
{
    public function answers()
    {
        return $this->hasMany('App\Answer');
    }
}

also I have Answer model , in this each answer belong to a question.

class Answer extends Model
{
    //
    public function question()
    {
        return $this->belongsTo('App\Question');
    }

}

So what i am trying to do is I want to fetch a question by it's id and it should have all the answers that belong to this particular question and together I want to pass it to my view.

Here is what I have Done so far

 public function show($id)
    {
      $questions = Question::with('questions')
                           ->join('answers', 'answers.question_id' , '=' , $id)
                           ->select('questions.id', 
                                        'questions.ask_question',
                                        'answers.user_id',
                                        'answers.aanswer',
                                        'answers.created_at')
                           ->where('questions.id' , '=', 'answers.question_id')
                           ->get();



return view('pages.show', ['questions' => $questions , 'user' => Auth::user()]);
    }

I have tried several other way but that didn't work


Solution

  • You can just fetch the question and use the relation in the view.

    public function show($id)
    {
         $question = Question::find($id);
         if ( ! $question) {
             abort(404);
         }
    
         return view('pages.show', compact('question'));    
    }
    

    And in your model you can do something like:

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

    Btw, there's no need to assign the Auth::user() to the view, the Auth facade is available there as well. You can also just use the helper method auth().

    <p>{{ Auth::user()->email }}</p>
    

    or

    <p>{{ auth()->user()->email }}</p>
    

    Will work just fine.