Many To Many

What is Many To Many?

A Many To Many relationship occurs when a record in one table can relate to many records in another table and vice versa.

👉 Example:

  • A Student can enroll in many Courses.
  • A Course can have many Students.

This relationship requires a pivot table (in Laravel usually named course_student).

Students ↔ Courses  

Flow diagram


Migration:

Use this command to generate a migration for creating a tables:

php artisan make:migration create_onetomany_manytoone_tables


Migration File

public function up(): void
{
    Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
    });

    Schema::create('courses', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->timestamps();
    });

    // Pivot table
    Schema::create('course_student', function (Blueprint $table) {
        $table->id();
        $table->foreignId('student_id')->constrained()->onDelete('cascade');
        $table->foreignId('course_id')->constrained()->onDelete('cascade');
        $table->timestamps();
    });
}

public function down(): void
{
    Schema::dropIfExists('course_student');
    Schema::dropIfExists('courses');
    Schema::dropIfExists('students');
}


Run Migration

php artisan migrate

Tables

students table
id name created_at updated_at
courses table
id title created_at updated_at
course_student table
id student_id course_id created_at updated_at
  • course_student.student_id is a foreign key referencing students.id.
  • course_student.course_id is a foreign key referencing courses.id.

Model:

Generate a model with Artisan:

php artisan make:model Student
php artisan make:model Course

This generates 2 files Student.php and Course.php


Student.php

namespace App\Models;

use App\Models\Course;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $fillable = ['name'];

    public function courses() {
        return $this->belongsToMany(Course::class, 'course_student');
    }
}


Course.php

namespace App\Models;

use App\Models\Student;
use Illuminate\Database\Eloquent\Model;

class Course extends Model
{
    protected $fillable = ['title'];

    public function students() {
        return $this->belongsToMany(Student::class, 'course_student');
    }
}

CRUD Examples

Create (Attach Student to Course)

use App\Models\Course;
use App\Models\Student;

// Create Student
$student = Student::create(['name' => 'John']);

// Create Course
$course = Course::create(['title' => 'Java']);

// Attach
$student->courses()->attach($course->id);
Output:
students table
id name created_at updated_at
1 John 2025-08-17 20:38:58 2025-08-17 20:38:58
courses table
id title created_at updated_at
1 Java 2025-08-17 20:38:58 2025-08-17 20:38:58
course_student table
id student_id course_id created_at updated_at
1 1 1 2025-08-17 20:38:58 2025-08-17 20:38:58

Read (Get Related Data)

use App\Models\Student;
use App\Models\Course;

// Get all courses of a student
$student = Student::find(1);
foreach ($student->courses as $course) {
  echo $course->title;
}

// Get all students of a course
$course = Course::find(1);
foreach ($course->students as $student) {
  echo $student->name;
}

Update (Sync Courses for a Student)

use App\Models\Student;
use App\Models\Course;

// Replace student’s courses with new ones
// Create Course
$course = Course::create(['title' => 'Laravel']);
$course = Course::create(['title' => 'PHP']);
$student = Student::find(1);
$student->courses()->sync([1, 2, 3]); // keeps only these
Output:
students table
id name created_at updated_at
1 John 2025-08-17 20:38:58 2025-08-17 20:38:58
courses table
id title created_at updated_at
1 Java 2025-08-17 20:38:58 2025-08-17 20:38:58
2 Laravel 2025-08-17 20:38:58 2025-08-17 20:38:58
3 PHP 2025-08-17 20:38:58 2025-08-17 20:38:58
course_student table
id student_id course_id created_at updated_at
1 1 1 2025-08-17 20:38:58 2025-08-17 20:38:58
2 1 2 2025-08-17 20:38:58 2025-08-17 20:38:58
3 1 3 2025-08-17 20:38:58 2025-08-17 20:38:58

Delete (Detach Student from Course)

use App\Models\Student;

$student = Student::find(1);
$student->courses()->detach(2); // remove course id 2 only

// or remove all courses ids in course_student table
$student->courses()->detach();

// Delete Student (will cascade course_student also if set cascade)
$student->delete()


Similarly Courses
$course = Course::find(1);
$course->students()->detach(2); // remove student id 2 only

// or remove all students ids in course_student table
$course->students()->detach();

// Delete Course (will cascade course_student also if set cascade)
$course->delete()

Eager loading (optimizes queries)

use App\Models\Student;
use App\Models\Course;

// Get all courses of a student
$student = Student::with('courses')->find(1);
foreach ($student->courses as $course) {
  echo $course->title;
}

// Get all students of a course
$course = Course::with('students')->find(1);
foreach ($course->students as $student) {
  echo $student->name;
}

Always use with() when fetching related data in bulk.


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.