Intermediate LevelLaravel
How do Polymorphic Relationships (morphTo, morphMany) work in Eloquent?
❓ Interview Prompt: Explain Polymorphic relationships, morphTo(), morphMany(), morphToMany(), commentable_type and commentable_id columns, and Relation::enforceMorphMap().
Polymorphic relationships allow a child model to belong to more than one type of parent model using a single association.
Structure:
For a 'Comment' model belonging to both 'Post' and 'Video' models, the 'comments' table contains 'commentable_type' ('AppModelsPost') and 'commentable_id' ('42') columns.
Best Practice: Use 'Relation::enforceMorphMap()' to replace full PHP class names with clean aliases ('post', 'video').
Code Implementation Example
php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsMorphTo;
class Comment extends Model
{
public function commentable(): MorphTo {
return $this->morphTo();
}
}💡Polymorphic MorphTo relationship on Comment model.
🎯 Interview Key Takeaway
Use Polymorphic relationships (morphTo, morphMany) to share child models (comments, images) across multiple parent model types.
#Polymorphic#morphTo#Eloquent#Intermediate
Back to all Laravel Questions→