A MorphOne relationship is a one-to-one polymorphic relationship, where a model can belong to more than one type of model using a single association.
Real-World Examples
- User → Profile Image
- Product → Image
- Blog Post → Thumbnail
- Course → Banner Image
Instead of creating multiple image tables, we use one images table.
1.When to Use morphOne
Use morphOne when:
- One model has only one related record
- Multiple models share the same related table
- You want clean & reusable database design
2. Example Scenario (User & Product Image)
✔ One image table
✔ Many parent models
3. Database Structure
users table
products table
images table (Polymorphic)
📌 imageable_id → parent ID
📌 imageable_type → parent model class
4.Create Models & Migrations
images migration
Run:
5.Define Relationships in Models
Image.php
User.php
Product.php
6.How Laravel Stores Data
| Column | Value |
|---|---|
| imageable_id | 1 |
| imageable_type | App\Models\User |
or
| imageable_id | 5 |
| imageable_type | App\Models\Product |
