Melodia
2 months ago
195
2
Laravel

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

Posted 2 months ago by Melodia

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;

Please sign in or create an account to participate in this conversation.