The morphTo relationship is used in polymorphic relationships to define the inverse side, where a model can belong to multiple different model types.
Real-World Examples
- A Comment belongs to either a Post or a Video
- An Image belongs to either a User or a Product
- A Review belongs to either a Course or a Book
1.When to Use morphTo
Use morphTo when:
- A child model can belong to different parent models
- You want one table instead of many
- The parent model type is dynamic
2.Example Scenario (Comments System)
✔ One comments table
✔ Multiple parent models
3.Database Structure
posts table
videos table
comments table
📌 commentable_id → parent ID
📌 commentable_type → parent model class
4.Create Models & Migrations
comments migration
Run:
5.Define morphTo in Child Model
Comment.php
✔ This allows Laravel to determine the parent dynamically.
