A Laravel package for adding tags to Eloquent models using polymorphic relationships.
You can install the package via Composer:
composer require sourcedopen/laravel-tagsThe package will automatically register its service provider.
Publish and run the migrations:
php artisan vendor:publish --tag="tags-migrations"
php artisan migrateUse the HasTags trait in any model you want to be taggable:
use Illuminate\Database\Eloquent\Model;
use SourcedOpen\Tags\Traits\HasTags;
class Post extends Model
{
use HasTags;
}use SourcedOpen\Tags\Models\Tag;
$tag = Tag::create([
'name' => 'Laravel',
'color' => '#FF2D20', // Optional hex color code
]);// Attach a single tag
$post->attachTags($tag->id);
// Attach multiple tags
$post->attachTags([$tag1->id, $tag2->id]);// Detach a single tag
$post->detachTags($tag->id);
// Detach multiple tags
$post->detachTags([$tag1->id, $tag2->id]);// Sync tags (removes all existing and attaches the provided ones)
$post->syncTags([$tag1->id, $tag2->id]);// Get all tags for a model
$tags = $post->tags;
// Query with tags
$posts = Post::whereHas('tags', function ($query) {
$query->where('name', 'Laravel');
})->get();composer testOr run Pest directly:
./vendor/bin/pestThis package uses Laravel Pint for code styling:
./vendor/bin/pintThe MIT License (MIT). Please see License File for more information.