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

DInu98's avatar

How to retrieve many to many relationship Data

i have student table and course table, also my pivot table is student_course, so I want to get list of students names who enroll with the relevant course. please help me

0 likes
3 replies
Dunsti's avatar
Dunsti
Best Answer
Level 6

1.) Your Models need to define the relationships :

example (you need this in both Models):

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

2.) your pivot-table needs to be course_student (alphabetical order of tablenames)

3.) access your courses like that:

use App\Models\Student;

$student = Student::find(1);

foreach ($student->courses as $course) {
    //
}

See Documentation here: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

1 like
DInu98's avatar

thank you so much. yeah my pivot table is course_student. actually i need like this i want select course in dropdown and table will be show all students list who are enroll with selected course

DInu98's avatar
  @if($courses->count())
              
            @foreach ($courses->students as $course)
                <tr>
                  <td>{{ $course->id }}</td>
                  <td>{{ $course->FullName}}</td>
                  <td>
                      <button class="btn btn-success">Edit</button>
                  </td>
                  <td>
                    <button class="btn btn-danger ml-3">Delete</button>
                  </td>
                </tr>
            @endforeach

Please or to participate in this conversation.