What is Polymorphic Relationships in Eloquent?
Why Interviewers Ask This
This tests whether you can apply Laravel knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
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.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.