📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Laravel Framework Polymorphic Relationships

Polymorphic Relationships

6 min read
Relate a single model to multiple types (Post, Video) using polymorphic hasMany and morphTo.

Polymorphic Relationships

// Comments can belong to Post or Video
class Comment extends Model {
    public function commentable(): MorphTo {
        return $this->morphTo();
    }
}

class Post extends Model {
    public function comments(): MorphMany {
        return $this->morphMany(Comment::class, "commentable");
    }
}

class Video extends Model {
    public function comments(): MorphMany {
        return $this->morphMany(Comment::class, "commentable");
    }
}

// Migration — comments table needs:
$table->morphs("commentable"); // adds commentable_id + commentable_type

// Usage
$post->comments()->create(["body" => "Great post!"]);
$video->comments()->create(["body" => "Great video!"]);

// All comments (morphTo auto-resolves the model)
$comment->commentable; // returns Post or Video