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

lucasweaver's avatar

Relationship returns "Attempt to read property "id" on null" but works in controller and printing variable in view

I have an index page for "Quiz Assignments" in which I'm trying to access the parent "Quiz" in order to show the quiz name and other attributes in the index of the assignments.

Accessing the relationship works fine in the controller when doing dd(); and if I simply print {{ $assignments }} in the view all of the data shows up. But when trying to foreach and then {{ $assignments->quiz->id }} I get "Attempt to read property "(doesn't matter which one and they all exist)" on null.

The view:

<x-layouts.app> <x-dashboard.index :user="$user"> <x-slot name="title"> Quizzes </x-slot> @foreach($assignments as $assignment) {{ $assignment->id }} {{ $assignment->quiz->id }} @endforeach </x-dashboard.index> <x-alerts.success > </x-alerts.success> </x-layouts.app>

Controller:

``public function quizTest() { $user = auth()->user();

    $assignments = QuizAssignment::with('quiz')->where('user_id', $user->id)->get();

    return view('dashboard.quizzes.test', ['user' => $user, 'assignments' => $assignments]);

}``

The Quiz Model:

public function assignments() { return $this->hasMany(QuizAssignment::class); }

The Assignment Model:

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

I've rewritten all of this a million times due to this issue, just trying to find out what the problem is, but I'm afraid I'm now at my wits end 🙈

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

you have an assignment with no quiz

you can find out which one with the null coalesce operator

{{ $assignment->quiz->id ?? 'none'}}
2 likes
lucasweaver's avatar

@Snapey all the assignments had quiz_id so I didn't notice, but indeed the parent quiz had been deleted. Thank you!!

MohamedTammam's avatar
  1. Clear the views cache
  2. Make sure you're calling the right view file
  3. Make sure that assignments has a quiz.

Please or to participate in this conversation.