A many-to-many relationship means multiple records in one table can be associated with multiple records in another table.
Real-World Examples
- A Student can enroll in many Courses
- A Course can have many Students
- A User can have many Roles
- A Product can have many Tags
1.Database Design (VERY IMPORTANT)
Many-to-Many relationships require 3 tables:
- First main table
- Second main table
- Pivot table (middle table)
Example: Students & Courses
students table
courses table
course_student (pivot table)
📌 Pivot table name rule:
- Alphabetical order
- Singular table names
✔ course_student (NOT student_course)
2.Create Models & Migrations
Pivot migration
Pivot Table Migration Code
Run migrations:
3.Define Relationship in Models
Student Model
Course Model
4.How Laravel Understands the Relationship
Laravel automatically assumes:
| Item | Value |
|---|---|
| Pivot table | course_student |
| Foreign key (student) | student_id |
| Foreign key (course) | course_id |
If your names are custom, you must define them manually.
5.Fetch Related Data
Get all courses of a student
Loop through data
Get all students of a course
6.Eager Loading (Performance Optimization)
❌ Wrong way (N+1 problem)
