Tags System (Pivot)
A flexible tagging system using a many-to-many pivot table. Posts and snippets can both be tagged with the same tags.
ERD Concept
Many-to-Many with shared pivot: Posts belong to many tags, snippets belong to many tags. Separate pivot tables for each relationship.
Tables
tags
id
name
slug
timestamps
topic_tag
topic_id (FK)
tag_id (FK)
timestamps
snippet_tag
snippet_id (FK)
tag_id (FK)
timestamps
Relationships
- Tag belongsToMany Topic (topic_tag)
- Tag belongsToMany Snippet (snippet_tag)
- Topic belongsToMany Tag
- Snippet belongsToMany Tag
Migration
Migration
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->timestamps();
});
Schema::create('topic_tag', function (Blueprint $table) {
$table->foreignId('topic_id')->constrained()->cascadeOnDelete();
$table->foreignId('tag_id')->constrained()->cascadeOnDelete();
$table->primary(['topic_id', 'tag_id']);
$table->timestamps();
});
Schema::create('snippet_tag', function (Blueprint $table) {
$table->foreignId('snippet_id')->constrained()->cascadeOnDelete();
$table->foreignId('tag_id')->constrained()->cascadeOnDelete();
$table->primary(['snippet_id', 'tag_id']);
$table->timestamps();
});