PHP

Implementing Polymorphic Many-to-Many Relationships

Structure databases and models for polymorphic many-to-many relationships, allowing a single model to be associated with multiple different model types via a pivot table.

/* Migration for Taggable Pivot Table */
Schema::create('taggables', function (Blueprint $table) {
    $table->foreignId('tag_id')->constrained()->onDelete('cascade');
    $table->morphs('taggable'); // Adds taggable_id (int) and taggable_type (string)
    $table->timestamps();
});

/* App\Models\Tag.php */
class Tag extends Model
{
    public function posts()
    {
        return $this->morphedByMany(Post::class, 'taggable');
    }

    public function videos()
    {
        return $this->morphedByMany(Video::class, 'taggable');
    }
}

/* App\Models\Post.php */
class Post extends Model
{
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

/* App\Models\Video.php (similar to Post.php) */
class Video extends Model
{
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

// Usage Example
$post = Post::find(1);
$post->tags()->attach(1); // Attach Tag with ID 1 to Post with ID 1

$tag = Tag::find(1);
foreach ($tag->posts as $post) {
    echo $post->title . '
';
}
foreach ($tag->videos as $video) {
    echo $video->title . '
';
}
How it works: This snippet illustrates a polymorphic many-to-many relationship, useful when a single model (e.g., `Tag`) can be associated with multiple other models (e.g., `Post`, `Video`) through a common pivot table (`taggables`). The `morphs()` method in the migration adds `taggable_id` and `taggable_type` columns. `morphToMany()` and `morphedByMany()` methods define the relationship on the respective models, allowing flexible associations and retrieval.

Need help integrating this into your project?

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

Hire DigitalCodeLabs