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

Melodia's avatar

How do i print an inventory list using many to many relationships

I have a student and task table, and model. Created a pivot table called student_task and here is how i set up the relationship:

class Task extends Model {
    public function students() {
        return $this->belongsToMany(Student::class);
    } .  
}

class Student extends Model{
    public function tasks() {
        return $this->belongsToMany(Task::class);
    }
}

How can I print a list of all students and associated task? In a way, I would want to see the student and task name.

I tried this:

Route::get('student-tasks', function() {
    $students = Student::all();
    foreach($students->tasks as $task) {
        echo $task->name;
    }
});

When I hit the url, I get the following error:

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

How can I print a list of all students and associated task?

Note: if I try the code below, I get a list of tasks associated to the user.

$student = Student::first();

return $student->tasks;
0 likes
2 replies
marbobo's avatar

can you try this?

Route::get('student-tasks', function() {
    $students = Student::with('tasks')->get();
    foreach($students->tasks as $task) {
        echo $task->name;
    }
});

notice that you need to use get() instead of all() if you want to use with to include the tasks on your eagier loading

Please or to participate in this conversation.