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

ayekoto's avatar

pls help query this ?, asked earlier but no valid assistance yet

i have a model: course, assignment, user(student)

And thier relationships below:

#User.php
public function courses()
{
    return $this->belongsToMany('App\Course');
}
#Course
public function students()
{
    return $this->belongsToMany('App\User');
}
#Assignment
public function course()
{
    return $this->belongsTo('App\Course');
}

And my tables look like:

course_student: student_id, course_id
assignments: course_id, name, download_path

Now the challenge i have here is that:

On the assignment download page, i want it possible that for each student, The assignment that will be display to the view for download will only be the assignments belonging to the courses the student is offering...

i asked earlier but was told to implement but after reading laravel docs on query builder and join.. Still havent gotten a way to resolve this.. Pardon i never used joined before, so any assistance will be appreciated.

Thanks

0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122

Perhaps you should have a relationship,

#Course
public function assignments()
{
    return $this->hasMany('App\Assignment');
}

Then you can query it something like;

    $student = Student::with('courses', 'courses.assignments')->findOrFail($id)

Then the returned collection should contain the student record, their courses and the assignments of those courses.

You can then list the assignments with (or without) the course name

    @forelse($student->courses as $course)
        // display the course details
        @forelse($course->assignments as $assignment)
            //display the assignments for this course
        @empty 
            <p>Yay, no assignments</p>
        @endforelse 
    @empty 
        <p>Hey dude - get yourself a course already</p>
    @endforelse
 

props to @codebyjeff for the @ forelse tip

*** UNTESTED ***

Please or to participate in this conversation.