What Are Polymorphic Relations?
A polymorphic relation lets a single model belong to more than one other model using the same association. The classic example: comments that can belong to either aPost or a Video — without needing a separate post_comments and video_comments table.
How It Works
Two special columns store the type and ID of the parent:| Column | Example Value |
|---|---|
commentable_type | 'Post' or 'Video' |
commentable_id | 42 |
1. Migration
2. Models
Comment — the “child” side, usesmorphTo:
morphMany:
3. Creating Polymorphic Records
4. Querying
Load comments for a post:5. morphOne — Single Polymorphic Child
Use morphOne when only one child record exists per parent — for example, each post has one FeaturedImage:
Common Use Cases
| Polymorphic relation | Example |
|---|---|
| Comments on posts and videos | morphMany / morphTo |
| Tags on any model | morphMany / morphTo |
| Likes on posts, comments, videos | morphMany / morphTo |
| Featured image for posts and products | morphOne / morphTo |
| Notifications for any actor | morphMany / morphTo |
Important: Register Your Models
Polymorphic resolution works by looking up model classes by name in the registry. Make sure every model involved in the relation hasstatic { this.register(); }:
