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

ayekoto's avatar

some issues query many-to-many relationship with error : Trying to get property of non-object

hi everyone,

i have three models which are user, course, semester and course_user, (which i named scores), Then i created a score model for my pivot table, So my score can belong to a semester, making it 4 models

Lemme show the code i used in defining the relationship User.php

    /**
     * a user belongs to many courses
     * 
     * @return 
     */
    public function studentCourses()
    {
        return $this->belongsToMany('App\Course','scores','student_id','course_id')->withPivot('semester_id')->withTimestamps();
    }

    /**
     * a user has many scores
     * 
     * @return 
     */
    public function scores()
    {
        return $this->hasMany('App\Score', 'student_id');
    }

Course.php

    /**
     * a course belongs to many students
     * 
     * @return 
     */
    public function courseStudents()
    {
        return $this->belongsToMany('App\User', 'scores','course_id','student_id')->withPivot('semester_id')->withTimestamps();
    }


    /**
     * a course belongs to many score 
     * 
     * @return 
     */
    public function scores()
    {
        return $this->belongsToMany('App\Score', 'scores', 'course_id', 'student_id')->withPivot('semester_id')->withTimestamps();
    }

score.php

    /**
     * a course belongs to a user
     * 
     * @return 
     */
    public function student()
    {
        return $this->belongsTo('App\User', 'student_id');
    }

    /**
     * a course belongs to a course
     * 
     * @return 
     */
    public function course()
    {
        return $this->belongsTo('App\Course', 'course_id');
    }

So in my repository, i did

    /**
     * fetch user with scores for the current semester
     * 
     * @return 
     */
    public function fetchUserScoresForCurrentSemester($slug, $semester_id)
    {
        return User::with(['scores.course' => function ($query) use ($semester_id) {

            $query->where('semester_id', $semester_id);

        }, 'studentprofile'])->where('slug', $slug)->first();
    }

Then in my controller

        $currentSemester = $this->courseRepo->fetchCurrentSemester();

        $user = $this->userRepo->fetchUserScoresForCurrentSemester($slug, $currentSemester->id);

        return view('student.course-success', compact('user'));     

here is my view to display result

<table class="table table-bordered table-striped">
    <thead>
        <th><a href="#">Course Code:</a></th>
        <th><a href="#">Course Name:</a></th>
        <th><a href="#">Lecturer Signature:</a></th>
        
    </thead>
    <tbody>
    @foreach($user->scores as $score)
        <tr>
            <td>{{$score->course->code}}</td><td>{{$score->course->name}}</td><td></td>
        </tr>
    @endforeach
    </tbody>
</table>

So everything works well when a user register for first semester and it fetched the first semester course name and code

Now when i test with the same user having registered for second semester, i keep getting an error of

Trying to get property of non-object

but when i change the view to

    @foreach($user->scores as $score)
        <tr>
            <td>{{$score->course_id}}</td><td>{{$score->course_id}}</td><td></td>
        </tr>

it displays the course_id but i want it to also use it to display the name just like it worked when the same user register for first semester..

i just wish to get this work so i can move more, spent all day but to no avail..

This a call for rescue, thanks

0 likes
2 replies
ayekoto's avatar

wish some one can help with this, still not getting it to work

ayekoto's avatar
ayekoto
OP
Best Answer
Level 7

i got it solved..like

/**
     * fetch user with scores for the current semester
     * 
     * @return 
     */
    public function fetchUserScoresForCurrentSemester($slug, $semester_id)
    {
        return User::with(['studentCourses' => function ($query) use ($semester_id) {

            $query->wherePivot('semester_id', $semester_id);

        }, 'studentprofile'])->where('slug', $slug)->first();
    }

Please or to participate in this conversation.