PHP

Implement Flexible Polymorphic Relationships in Eloquent

Learn to build polymorphic one-to-many relationships in Laravel Eloquent, allowing a single model to belong to multiple types of other models on a single association.

// In your Comment model (App/Models/Comment.php)
class Comment extends Model
{
    public function commentable()
    {
        return $this->morphTo();
    }
}

// In your Post model (App/Models/Post.php)
class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

// In your Video model (App/Models/Video.php)
class Video extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

// Usage: Attach comments to posts or videos
$post = App\Models\Post::find(1);
$post->comments()->create(['body' => 'Great post!']);

$video = App\Models\Video::find(1);
$video->comments()->create(['body' => 'Awesome video!']);

// Retrieve the commentable parent
$comment = App\Models\Comment::find(1);
$parent = $comment->commentable; // This could be a Post or a Video instance

echo "Comment ID: " . $comment->id . "
";
echo "Comment Body: " . $comment->body . "
";
echo "Parent Type: " . get_class($parent) . "
";
echo "Parent ID: " . $parent->id . "
";
How it works: This snippet demonstrates how to implement polymorphic relationships in Laravel Eloquent. A polymorphic relationship allows a model (`Comment`) to belong to more than one other model (`Post`, `Video`) on a single association. The `morphTo()` method is used on the child model, while `morphMany()` or `morphOne()` is used on the parent models, linking them via `commentable_id` and `commentable_type` columns. This design pattern offers great flexibility when a single relationship type needs to apply to various different models.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs