morphToMany is a polymorphic many‑to‑many relationship in Laravel.It allows multiple different models to share a many‑to‑many relationship with another model using a single pivot table.
1. Real-World Example
Scenario: Tags System
- Posts can have many Tags
- Videos can have many Tags
- A Tag can belong to many Posts and Videos
Instead of:
- post_tag
- video_tag
We use one pivot table → taggables
2. Database Structure
Main Tables
posts
videos
tags
Pivot Table: taggables
Column Explanation
| Column | Purpose |
|---|---|
| tag_id | ID of the tag |
| taggable_id | ID of post or video |
| taggable_type | Model class (Post / Video) |
3. Migration Example
morphs('taggable') automatically creates:
- taggable_id
- taggable_type
