Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Dabbash's avatar

Property [id] does not exist on this collection instance.

Hi everyone,

What I want to achieve is to view all the answers under each question in the quiz,

In web.php:

Route::get('/{slug}', 'HomeController@showQuiz')->name('showQuiz');

In ShowQuiz function:

public function showQuiz($slug)

{

    $quiz = Quizzes::where('slug', $slug)->first();

    $questions = Questions::where('quiz_id', $quiz->id)->get();

    $answers = Answer::where('question_id', $questions->id)->get();

    return view('showQuiz', compact('quiz', 'questions', 'answers'));

}

But it gives me "Property [id] does not exist on this collection instance.", it refer it to -> $answers = Ans...

This is the code in showQuiz.blade.php:

@foreach($questions as $question)

                <p class="font-bold text-xl" style="text-align: right">{{$question->question_title}}</p>

                <img class="mr-2 rounded custom-img" src="{{asset('images/'.$question->background)}}">

            @foreach($answers as $answer)

                <img class="mr-2 rounded custom-img" src="{{asset('images/'.$answer->background)}}">

            @endforeach

    @endforeach
0 likes
15 replies
tykus's avatar
tykus
Best Answer
Level 104

Eager load the answers with questions

$questions = Questions::with('answers')->where('quiz_id', $quiz->id)->get();
@foreach($questions as $question)

     {{$question->question_title}}

     @foreach($question->answers as $answer) 
         // answer
     @endforeach 
@endforeach

The reason for the error was here $answers = Answer::where('question_id', $questions->id)->get();; $questions is a Collection of Question instances, so does not have an id property itself.

1 like
Sinnbeck's avatar

Just a quick code example for what @tykus is saying. Edit: beat me to it :D

    $questions = Questions::with('answers')->where('quiz_id', $quiz->id)->get();

//I assume you have this on the Question model
public function answers()
{
    return $this->hasMany(Answer::class);
}
1 like
automica's avatar

@tykus yours should be:

$questions = Questions::with('answers')->where('quiz_id', $quiz->id)->get();
@foreach($questions as $question)

     {{$question->question_title}}

     @foreach($question->answers as $answer)  // this bit needs $question->answers not $answers
         // answer
     @endforeach 
@endforeach
Dabbash's avatar

Thank you @tykus for your quick response, I did what you told me but I got this issue

Illuminate \ Database \ QueryException (42S22) SQLSTATE[42S22]: Column not found: 1054 Unknown column 'answers.questions_id' in 'where clause' (SQL: select * from answers where answers.questions_id in (3, 4, 5, 6))

I see that it tries to find questions_id and what I have is question_id, without 's'

Sinnbeck's avatar

Can you show the migration for the answers table?

Dabbash's avatar

This is the code: { class CreateAnswersTable extends Migration { /** * Run the migrations. * * @return void */

public function up()

{

    Schema::create('answers', function (Blueprint $table) {

        $table->bigIncrements('id');

        $table->string('slug');

        $table->integer('question_id');

        $table->string('answer_text');

        $table->string('is_correct');

        $table->string('background');

        $table->string('disc');

        $table->timestamps();

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('answers');
}

}

}

tykus's avatar

You relationship must be incorrectly setup. The following assumes you have a questions_id column (questions coming from the Questions model name) on the `answers table by convention:

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

Do you have something different in the Question model?

Ideally, your migration should create a foreign key for question_id to enforce referential integrity; i.e. an Answer can only be associated with a valid Question. This is simple with Laravel:

$table->foreignId('question_id')->constrained();

https://laravel.com/docs/8.x/migrations#foreign-key-constraints

1 like
Sinnbeck's avatar

It is because you arent following conventions. Your question model is called Questions not Question

public function answers()
{
    return $this->hasMany(Answer::class, 'question_id');
}
1 like
Dabbash's avatar

@tykus & @sinnbeck , thank you for all your response, you will find more details below.

This is all the codes in Answer Model

class Answer extends Model
{
   protected $fillable = [
       'question_id',
       'slug',
       'answer_text',
       'is_correct',
       'background',
       'disc',
   ];

public function sluggable()
{
    return [
        'slug' => [
            'source' => 'answer_text'
        ]
    ];
}

   public function questions(){
       return $this->belongsTo(Questions::class);
   }

}

and here all the code in Questions Model

class Questions extends Model
    {
        protected $fillable = [
        'question_title',
        'slug',
        'quiz_id',
        'background',
        ];

public function sluggable()
{
    return [
        'slug' => [
            'source' => 'question_title'
        ]
    ];
}

public function result(){
    return $this->hasMany(Result::class);
}

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

public function quiz(){
    return $this->belongsTo(Quizzes::class);
}

public function getQuestionById($id){
    return Question::find($id);
}

}

When I view the questions separately in QuestionsController@show()

public function show(Questions $question)

{

    $answers = Answer::where('question_id', $question->id)->get();

    $result = Result::where('question_id', $question->id)->get();

    return view('admin.question.show', compact('question', 'answers', 'result'));
}

it retraive the all the answers without any issues.

But When I want to view all details of the quiz, like questions and answers on the same page it appears the issue

Sinnbeck's avatar

Yes and we just gave you the solution. Either rename Questions or give the foreign key manually like shown above

1 like
tykus's avatar

All of the answers in a single flat collection is not much good; better if each answer was in a Collection nested under the relevant Question. This is why I specifically mentioned about eager loading the answers with the questions because Laravel will nest the correct answers under each question instance

2 likes
Dabbash's avatar

Thank you so much, @tykus @sinnbeck, I updated AnswerTable and added 'question_id' in answer function and it works perfectly.

Appreciate your help ^^

Please or to participate in this conversation.