🔴 Laravel
Intermediate
What is Polymorphic Relationships in Eloquent?
Answer
Polymorphic relationships allow a model to belong to more than one other type of model on a single association. Example: a Comment model that can belong to either a Post or a Video. The comments table has commentable_id and commentable_type columns. Define in Comment: public function commentable() { return $this->morphTo(); }. Define in Post: public function comments() { return $this->morphMany(Comment::class, "commentable"); }. Access comments on a post: $post->comments. Access the parent: $comment->commentable. Use morph map to map type strings to class names: Relation::morphMap(["post" => Post::class]) — prevents class name coupling in the database.