A one-to-many relationship means one record in a table can be related to multiple records in another table.
Real-World Examples
- One User has many Posts
- One Category has many Products
- One Course has many Lessons
- One Order has many Order Items
1.Database Table Structure
Example: Users & Posts
users table
posts table
👉 Foreign Key Rule
The child table (posts) must contain the foreign key (user_id).
2.Create Models & Migrations
users migration
posts migration
Run migration:
3.Define Relationship in Models
Parent Model (User)
Child Model (Post)
4.How Laravel Knows the Relationship
Laravel automatically assumes:
| Part | Value |
|---|---|
| Foreign key | user_id |
| Local key | id |
| Table name | posts |
If naming is custom, you must define them manually.
5.Fetching Data (Read Operations)
Get all posts of a user
Loop through posts
6.Eager Loading (IMPORTANT for Performance)
❌ N+1 Problem
