Skip to content
Laravel Packagev6.0.0MIT License

Laravel Tags

Tags for any Eloquent model. Add the HasTags trait, then attach, detach and sync tags by name, by Tag model or by key. Names are normalized, so spelling and case never create a duplicate; types, aliases and translations decide which tag a name means; and the database keeps each name to one tag even when requests race.

Typed Tags

The same name in two types is two tags; untyped tags work as well.

Name Identity

Unicode normalization, case folding, aliases and translations resolve to one tag.

Aliases and Merging

Add aliases, rename with the old name kept, and merge duplicates.

Tag Policies

Attach existing tags only, globally or per model.

Search and Related

Search, suggest, rank popular tags and find related tags and models.

Quick Tip

A string is always a tag name and an integer always a tag key, so attachTag('2024') tags the model with the name "2024", never with the tag whose key is 2024.

#Installation

Install the package with Composer and run the migrations.

#Requirements

  • PHP 8.0
  • Laravel 6.x
  • pharaonic/laravel-sluggable (installed with the package) for tag slugs
  • Optional: pharaonic/laravel-translatable to translate tag names

#Composer Installation

Terminal
composer require pharaonic/laravel-tags

The service provider is registered automatically.

#Run Migrations

Terminal
php artisan migrate

The migrations create three tables:

TableHolds
tagsOne row per tag: name, slug, type, position and metadata
tag_namesEvery name a tag answers to: its name, its translations and its aliases, with a unique index on type and normalized name
taggablesOne row per tagged model, with the tagging's position and metadata
Existing tables

Each migration refuses to run when its table exists. pharaonic/laravel-taggable and spatie/laravel-tags both use tags and taggables: rename or drop them first (see the Upgrade Guide), or set other table names in the configuration.

#Publish Files

Publish only what you need to change:

Terminal
php artisan vendor:publish --tag=tags-config
php artisan vendor:publish --tag=tags-migrations
php artisan vendor:publish --tag=tags-translations

The configuration is published to config/pharaonic/tags.php. The laravel-tags tag publishes all three.

Installation Complete

Add HasTags to a model and start tagging.

#Configuration

Every option lives under pharaonic.tags. Set them in the published config/pharaonic/tags.php before running the migration when they change the schema (tables, key types, connection).

KeyDefaultDescription
connectionnullThe connection of the three tables; null is the default connection. The tagged models' tables must be in the same database, because the query scopes join taggables in the model's query.
models.tagModels\Tag::classThe tag model; a subclass adds behaviour or Laravel Translatable.
models.tag_nameModels\TagName::classThe model of tag_names.
models.taggableModels\Taggable::classThe pivot model of taggables.
tables.tags / tables.tag_names / tables.taggablestags / tag_names / taggablesTable names.
tag_key_typeintegerKeys of tags: integer, uuid (time-ordered version 7) or ulid.
key_typeintegerKeys of tagged models: integer, uuid, ulid, or string to tag models with different key types in one table.
eventstrueDispatch the package events.
normalizerSupport\TagNameNormalizer::classThe class that turns a name into its identity (implements Contracts\TagNormalizer).
slug['on_update' => false]Laravel Sluggable options for the slug: separator, on_update, max_length, ascii_only, ascii_lang.
policy.auto_createtrueCreate tags for unknown names, or refuse them.
cleanup_on_soft_deletefalseDetach the tags of a soft-deleted model.
cleanup_on_force_deletetrueDetach the tags of a deleted (or force-deleted) model.
config/pharaonic/tags.php
1return [
2 // ...
3 'key_type' => 'string',
4 
5 'policy' => [
6 'auto_create' => false,
7 ],
8];
Changing the normalizer

The normalized form of every name is stored. Changing the normalizer after tags exist does not rewrite those values, so names may stop matching their tags.

#Basic Usage

Add HasTags to any model.

app/Models/Post.php
1namespace App\Models;
2 
3use Illuminate\Database\Eloquent\Model;
4use Pharaonic\Laravel\Tags\Concerns\HasTags;
5 
6class Post extends Model
7{
8 use HasTags;
9}

#Attach, detach, sync and clear

Tags are given as names, Tag models, integer keys, or arrays and collections of these. Missing names are created (unless the policy says otherwise).

1use Pharaonic\Laravel\Tags\Models\Tag;
2 
3$post->attachTags(['Laravel', 'PHP']); // Collection of the two tags
4$post->attachTag('laravel'); // the same Laravel tag: it stays where it is
5$post->attachTag(Tag::findOrCreate('Pest'));
6 
7$post->detachTag('php'); // true: the post had it
8$post->detachTags(['pest', 'unknown']); // 1: how many the post lost
9 
10$result = $post->syncTags(['Laravel', 'Livewire']);
11$result['attached']->pluck('name'); // ["Livewire"]
12$result['detached']; // tags the post lost
13$result['updated']; // tags whose metadata changed
14 
15$post->clearTags(); // how many it lost

#Read tags

1$post->tags; // in the post's order, with pivot position and metadata
2$post->hasTag('LARAVEL'); // true
3$post->hasAnyTags(['vue', 'livewire']); // true
4$post->hasAllTags(['laravel', 'vue']); // false
5 
6Post::with('tags')->get(); // eager loading
7Post::withAnyTags(['laravel', 'php'])->get();

hasTag(), hasAnyTags() and hasAllTags() use the loaded tags relation when it is loaded, and query the database otherwise.

#Input rules

GivenMeans
'php', '2024'A name, always; never a key
5The tag with the integer key 5 (integer tag keys only)
Tag modelThat tag; the way to give tags with UUID or ULID keys
null, floats, arrays inside arrays, blank namesRefused with InvalidArgumentException

A key or model that does not exist throws ModelNotFoundException, and nothing is attached.

#Types and Names

#Types

A tag has a type, or none. The same name in two types is two tags.

1$post->attachTag('Laravel'); // untyped
2$post->attachTag('Laravel', 'framework'); // another tag, of the type "framework"
3 
4$post->tagsOfType('framework'); // from the loaded relation
5$post->tagsOfType(null); // the untyped tags

The type argument works the same way everywhere:

MethodType omittednull'topic'
attachTag(), attachTags(), findOrCreate()untypeduntypedthe type
detachTag(s)(), syncTags(), clearTags(), hasTag() and the scopesevery type (Tag::ANY_TYPE)untyped onlythe type

A type is a non-empty string of up to 64 characters without surrounding spaces, never '*' (that is Tag::ANY_TYPE). The type of a saved tag cannot change.

#Name identity

Two names are the same tag when their normalized forms match. The default normalizer:

  1. Applies Unicode NFC, turns control and invisible format characters (such as zero-width spaces) into spaces, collapses whitespace and trims: this is the name that is stored and shown.
  2. Applies NFKC, full Unicode case folding and NFKC again for the identity.
1$tag = Tag::findOrCreate(' Café Society ');
2$tag->name; // "Café Society"
3 
4Tag::findByName('CAFÉ SOCIETY'); // the same tag
5Tag::findOrCreate('Straße');
6Tag::findByName('STRASSE'); // the Straße tag: full case folding

A name has at least one visible character and up to 255 characters. When the same name appears twice in one call, the first spelling is the one a new tag gets.

#Custom normalizer

Implement Contracts\TagNormalizer and set pharaonic.tags.normalizer.

app/Tags/HashtagNormalizer.php
1namespace App\Tags;
2 
3use Pharaonic\Laravel\Tags\Contracts\TagNormalizer;
4use Pharaonic\Laravel\Tags\Support\TagNameNormalizer;
5 
6class HashtagNormalizer implements TagNormalizer
7{
8 public function display(string $name): string
9 {
10 return ltrim((new TagNameNormalizer)->display($name), '#');
11 }
12 
13 public function normalize(string $name): string
14 {
15 return (new TagNameNormalizer)->normalize($this->display($name));
16 }
17}

#Slugs

Slugs come from Laravel Sluggable and are unique across all types: the same name in two types gets laravel and laravel-2. They do not change on rename unless pharaonic.tags.slug.on_update is true.

#Rename

1$tag->rename('Laravel Framework'); // the old name is forgotten
2$tag->rename('Laravel', true); // the old name stays as an alias

Renaming to a name another tag of the type has throws TagConflictException.

#Aliases and Merging

#Aliases

An alias is another name of a tag. It resolves to the tag everywhere a name is accepted: attach, sync, hasTag(), the scopes, search and suggestions.

1$tag = Tag::findOrCreate('JavaScript');
2$tag->addAlias('JS'); // TagName
3$tag->addAlias('ecmascript', 'en'); // an alias with a locale
4 
5$post->attachTag('js'); // the JavaScript tag
6Tag::findByName('ECMAScript'); // the JavaScript tag
7 
8$tag->aliases; // TagName models, by normalized name
9$tag->removeAlias('js'); // true

Adding an alias the tag already has changes nothing. An alias is scoped to the tag's type, and it can never be the name or alias of another tag there: that throws TagConflictException. Since an alias is a name and not a tag, aliases can never chain or loop.

#Merging

Merge a duplicate into the tag you keep. Its taggings move to the target in one transaction.

1$source = Tag::findByName('js');
2$target = Tag::findByName('JavaScript');
3 
4$source->mergeInto($target); // the target, refreshed
5$source->mergeInto($target, true); // keep the source's names as aliases
WhatHappens
Models with only the sourceTheir tagging moves to the target, keeping position and metadata
Models with both tagsThe target's tagging stays as it is; the source's is dropped
Source aliasesMove to the target
Source name and translationsBecome aliases with true, dropped otherwise
Source slug, metadata, positionDropped with the source

Both tags must have the same type, and differ; otherwise InvalidArgumentException. Only TagsMerged is dispatched.

#Tag Policies

By default an unknown name creates a new tag. Set pharaonic.tags.policy.auto_create to false to attach existing tags only, or override it on one model with an autoCreatesTags() method:

app/Models/Article.php
1use Illuminate\Database\Eloquent\Model;
2use Pharaonic\Laravel\Tags\Concerns\HasTags;
3 
4class Article extends Model
5{
6 use HasTags;
7 
8 public function autoCreatesTags(): bool
9 {
10 return false;
11 }
12}

A name without a tag then throws TagPolicyException, and nothing of the write is saved:

1use Pharaonic\Laravel\Tags\Exceptions\TagPolicyException;
2 
3try {
4 $article->attachTags(['Laravel', 'Something new']);
5} catch (TagPolicyException $exception) {
6 $exception->getMessage(); // "The tags [Something new] do not exist, ..."
7}

Tag::findOrCreate() and Tag::bulkCreate() follow the configured auto_create.

Limits, allowed types and name rules belong in your own validation, for example 'tags' => 'array|max:5' and 'tags.*' => 'string|min:2|max:40'.

#Metadata and Ordering

#Tagging metadata

Each tagging can carry a JSON array, on the pivot.

1$post->attachTag('Laravel', null, ['weight' => 3, 'source' => 'editor']);
2 
3$post->tags->first()->pivot->metadata; // ["source" => "editor", "weight" => 3]

Giving metadata again replaces it; attaching without metadata keeps what is stored. syncTags($tags, $type, $metadata) sets the metadata of every given tag and reports the taggings whose metadata changed under updated. Metadata that cannot be encoded as JSON throws InvalidArgumentException.

The tag itself has a metadata array too:

1Tag::query()->create(['name' => 'PHP', 'metadata' => ['color' => '#777bb3']]);

#A model's order

A model keeps its tags in the order they were attached; $post->tags and pivot->position follow it. A sync keeps the order of the tags it keeps and adds new ones at the end.

1$post->reorderTags(['php', 'laravel']); // these first, the rest after them

#The global order

1Tag::reorder([$php, $laravel]); // positions 1, 2 (models or integer keys)
2Tag::query()->ordered()->get(); // by position, then name

#Querying

#Model scopes

Each scope takes names, models or keys and the type argument (every type when omitted).

1Post::withAnyTags(['laravel', 'php'])->get(); // at least one
2Post::withAllTags(['laravel', 'php'])->get(); // every one
3Post::withoutTags(['draft'])->get(); // none of them
4Post::withoutAnyTags()->get(); // no tag at all
5Post::withoutAnyTags('topic')->get(); // no tag of the type
6Post::withTagsCount()->get(); // a tags_count column
7Post::withAnyTags('laravel', 'framework')->get(); // in one type

An unknown name matches nothing: withAnyTags(['unknown']) finds no model, and withAllTags(['laravel', 'unknown']) finds none either. An empty list in withAnyTags() finds nothing.

#Tag scopes

1Tag::query()->ofType('topic')->get(); // null for untyped tags
2Tag::query()->ordered()->get();
3Tag::query()->popular()->limit(10)->get(); // with taggables_count, most used first
4Tag::query()->unused()->get(); // tags no model has

#Tagged models of a tag

1$tag->models(Post::class)->latest()->paginate();
2$tag->taggables()->count();

#Bulk Operations

Tag many models in a few queries. Models can be of several classes.

1use Pharaonic\Laravel\Tags\Models\Tag;
2 
3Tag::bulkCreate(['Laravel', 'PHP', 'laravel']); // 2 tags, in order, no duplicates
4 
5Tag::bulkAttach($posts, ['featured']); // taggings created
6Tag::bulkDetach($posts, ['draft']); // taggings removed
7 
8$result = Tag::bulkSync($posts, ['news', 'laravel']);
9$result['attached']; // counts
10$result['detached'];
11$result['updated'];
12$result['changes'][$post->getMorphClass()][$post->getKey()]; // attached, detached and updated collections

changes holds the models that changed, by morph type and then key, since models of two classes can share a key. bulkAttach() and bulkSync() accept a type and metadata like their single-model forms, and each model's auto_create applies.

Chunks

The models are written in chunks of 500 of one class, one transaction per chunk. When a chunk fails (a refused new name, a missing tag), nothing in that chunk is written, but earlier chunks stay written. Wrap the call in your own transaction for all-or-nothing.

#Translations

Tag names can be translated with pharaonic/laravel-translatable. Every translation is a name of the tag, so a tag created in English is found by its Arabic name too.

Terminal
composer require pharaonic/laravel-translatable

Make a tag model that translates name with the table strategy, and a model and table for its translations:

app/Models/Tag.php
1namespace App\Models;
2 
3use Pharaonic\Laravel\Tags\Models\Tag as BaseTag;
4use Pharaonic\Laravel\Translatable\Translatable;
5 
6class Tag extends BaseTag
7{
8 use Translatable;
9 
10 protected $translatables = ['name'];
11 
12 public function getTranslatableModel()
13 {
14 return TagTranslation::class;
15 }
16 
17 public function getTranslatableField()
18 {
19 return 'tag_id';
20 }
21}
app/Models/TagTranslation.php
1namespace App\Models;
2 
3use Illuminate\Database\Eloquent\Model;
4 
5class TagTranslation extends Model
6{
7 public $timestamps = false;
8 
9 protected $guarded = [];
10}

The translations table (tag_translations by Translatable's convention) has tag_id, locale and name columns. Then set the model in the configuration:

config/pharaonic/tags.php
1'models' => [
2 'tag' => App\Models\Tag::class,
3 // ...
4],

#Using translated tags

1$tag = new App\Models\Tag;
2$tag->setTranslation('name', 'en', 'Programming');
3$tag->setTranslation('name', 'ar', 'برمجة');
4$tag->save();
5 
6Tag::findByName('برمجة'); // the same tag
7app()->setLocale('ar');
8$post->attachTag('تصميم'); // a new tag, named in Arabic

The tags.name column keeps one canonical name (the current locale's when the tag is created). A translation cannot be another tag's name: saving it throws TagConflictException. Without Laravel Translatable installed, none of this is needed and the package never loads it.

#Events

Every event is dispatched after the outermost database transaction commits, and dropped when it rolls back. Outside a transaction it is dispatched right after the write.

EventPropertiesDispatched when
TagCreated$tagA tag is created
TagRenamed$tag, $previousNameA tag's name changes
TagDeleted$tagA tag is deleted
TagsMerged$source, $target, $movedTaggings, $keptNameAsAliasA tag is merged into another
TagAliasAdded$tag, $alias (TagName)An alias is added (not when it existed)
TagAliasRemoved$tag, $aliasAn alias is removed
TagsAttached$model, $tagsA model gained tags
TagsDetached$model, $tagsA model lost tags
TagsSynced$model, $attached, $detached, $updatedA sync changed a model's tags

All events are in the Pharaonic\Laravel\Tags\Events namespace.

app/Providers/EventServiceProvider.php
1use App\Listeners\RefreshTagCloud;
2use Pharaonic\Laravel\Tags\Events\TagsAttached;
3use Pharaonic\Laravel\Tags\Events\TagsDetached;
4 
5protected $listen = [
6 TagsAttached::class => [RefreshTagCloud::class],
7 TagsDetached::class => [RefreshTagCloud::class],
8];

#Turning events off

1Tag::withoutTagEvents(function () use ($posts) {
2 Tag::bulkAttach($posts, ['imported']);
3});

Set pharaonic.tags.events to false to dispatch none. A change made inside withoutTagEvents() stays silent even when its transaction commits after the callback returned.

Testing

Event::fake() does not stop a tag's names from being written: the package keeps them in Tag::save(), not in model event listeners. In tests that use RefreshDatabase, the events are dispatched as if its transaction were not there.

#Commands

tags:prune deletes taggings of models that no longer exist (left by mass deletes, which fire no model events) and tags no model has.

Terminal
php artisan tags:prune # report both
php artisan tags:prune --orphans --apply # delete orphaned taggings only
php artisan tags:prune --unused --apply # delete unused tags only
php artisan tags:prune --apply # both

Without --apply it only reports. It exits with 0, or 1 on an error.

Taggings of a type that is not a model class or morph alias, or whose table is on another connection, are skipped with a warning.

#Key Types and Morph Maps

#Keys of tagged models

key_type sets the type of taggables.taggable_id. Set it before the migration runs.

key_typeModels
integerInteger keys (default)
uuidUUID keys
ulidULID keys
stringAny mix, such as integer posts and UUID products, stored as strings of up to 64 characters

A model whose key does not fit the type is refused with InvalidArgumentException. With string on PostgreSQL, the relations and scopes compare keys as text, so with('tags'), withAnyTags(), withTagsCount() and relatedModels() work on every model.

#Keys of tags

tag_key_type is integer, uuid or ulid. UUID keys are version 7 and ULIDs are generated by the package, so both sort by creation time. Tags with UUID or ULID keys are given as Tag models; an integer is then refused, and a string is always a name.

#Morph maps

The taggable_type column stores the model's morph class, so registered aliases are used:

app/Providers/AppServiceProvider.php
1use Illuminate\Database\Eloquent\Relations\Relation;
2 
3Relation::morphMap([
4 'post' => App\Models\Post::class,
5]);

A morph class longer than 191 characters is refused; register a shorter alias.

#Custom models and tables

Extend the models and set them, and the table names, in the configuration:

app/Models/Tag.php
1namespace App\Models;
2 
3use Pharaonic\Laravel\Tags\Models\Tag as BaseTag;
4 
5class Tag extends BaseTag
6{
7 public function getUrlAttribute(): string
8 {
9 return url('/tags/'.$this->slug);
10 }
11}
config/pharaonic/tags.php
1'models' => ['tag' => App\Models\Tag::class],
2'tables' => ['tags' => 'labels', 'tag_names' => 'label_names', 'taggables' => 'labelables'],

#Integrity and Concurrency

The database, not a read before the write, keeps the data consistent:

  • tag_names has a unique index on type and normalized name, so a name, translation or alias belongs to one tag even when two requests create it at once. The loser of the race reuses the winner's tag.
  • taggables has a unique index on the model and the tag, so a model has a tag once.
  • Untyped tags store an empty string, not NULL, so the indexes cover them too.
  • Each write locks the tagged model's row before it reads the model's tags, so positions are computed by one writer at a time. This needs the model's table on the tags connection; a model on another connection is not locked.
  • A merge locks both tags, so attachments to the source wait and then land on the target.

#Retries

A write that opens its own transaction runs again after a lost race (a deadlock, a serialization failure, a lock timeout, MariaDB's error 1020, a busy SQLite database), up to 5 runs with a short random pause. Inside your transaction, it runs once in a savepoint and the error reaches you, since the database may have rolled back your transaction:

1use Illuminate\Support\Facades\DB;
2 
3DB::transaction(function () use ($post) {
4 $post->syncTags(['laravel', 'php']);
5 $post->update(['tagged_at' => now()]);
6}, 3); // let Laravel retry the whole transaction

These guarantees are checked by tests that run separate PHP processes at the same moment on MySQL, MariaDB, PostgreSQL and SQLite.

#API Reference

#HasTags

$tags is a name, Tag model, integer key, or an array or collection of these. $type defaults as described in Types and Names.

MethodDescriptionReturns
tags()The model's tags in its order, with pivot id, position, metadataTagsMorphToMany
tagsOfType(?string $type)Loaded tags of a type (null for untyped)Collection
attachTag($tag, ?string $type = null, ?array $metadata = null)Attach one tagTag
attachTags($tags, ?string $type = null, ?array $metadata = null)Attach tags after the othersCollection
detachTag($tag, ?string $type = '*')Whether the model had itbool
detachTags($tags, ?string $type = '*')How many the model lostint
syncTags($tags, ?string $type = '*', ?array $metadata = null)Keep only these tags (in the type)array of attached, detached, updated
clearTags(?string $type = '*')Detach every tag (of the type)int
hasTag($tag, ?string $type = '*')Whether the model has itbool
hasAnyTags($tags, ?string $type = '*')At least onebool
hasAllTags($tags, ?string $type = '*')Every one (true for none)bool
reorderTags($tags)Put these firstvoid
relatedModels(?string $type = '*', bool $similarity = false)Models sharing tagsBuilder
autoCreatesTags()Whether unknown names create tags; override per modelbool
scopeWithAnyTags($tags, $type), scopeWithAllTags, scopeWithoutTagsFilter models—
scopeWithoutAnyTags(?string $type = '*')Models without tags—
scopeWithTagsCount(?string $type = '*')Add tags_count—

#Tag

MethodDescriptionReturns
Tag::findByName(string $name, ?string $type = null)Through names, translations and aliases?Tag
Tag::findOrCreate(string $name, ?string $type = null)Find or create under the global policyTag
Tag::bulkCreate($names, ?string $type = null)Find or create manyCollection
Tag::bulkAttach($models, $tags, ?string $type = null, ?array $metadata = null)Taggings createdint
Tag::bulkDetach($models, $tags, ?string $type = '*')Taggings removedint
Tag::bulkSync($models, $tags, ?string $type = '*', ?array $metadata = null)Counts, and changes by morph type and keyarray
Tag::suggest(string $term, int $limit = 10, ?string $type = '*', ?string $locale = null)Prefix suggestionsCollection
Tag::reorder($tags)Global positions 1, 2, …void
Tag::withoutTagEvents(callable $callback)Run without package eventscallback result
rename(string $name, bool $keepOldNameAsAlias = false)RenameTag
addAlias(string $alias, ?string $locale = null)Add an aliasTagName
removeAlias(string $alias)Whether it had itbool
mergeInto(Tag $target, bool $keepNameAsAlias = false)Merge and delete this tagTag (the target)
deleteIfUnused()Delete when no model has itbool
related(?string $modelClass = null)Co-occurring tags with cooccurrencesBuilder
models(string $class)Tagged models of a classTagsMorphToMany
names(), aliases(), taggables()RelationsHasMany
scopeOfType, scopeOrdered, scopeSearch, scopePopular, scopeUnusedQuery scopes—
PropertyDescription
nameThe canonical name
slugThe slug
typeThe type, or null
positionThe global position
metadataAn array, or null
Tag::ANY_TYPE'*': every type

#Exceptions

ExceptionThrown when
TagConflictExceptionA name, alias or translation belongs to another tag
TagPolicyExceptionA name has no tag and auto_create is off
RetryableWriteExceptionA concurrent write changed what a write read; the package runs it again unless it ran inside your transaction
InvalidArgumentExceptionInvalid names, types, keys, metadata or input values
ModelNotFoundExceptionA given key or tag does not exist or is not visible

All package exceptions are in Pharaonic\Laravel\Tags\Exceptions.

#Examples

#1. Tagging posts from a form

app/Http/Controllers/PostController.php
1namespace App\Http\Controllers;
2 
3use App\Models\Post;
4use Illuminate\Http\Request;
5use Pharaonic\Laravel\Tags\Exceptions\TagPolicyException;
6 
7class PostController extends Controller
8{
9 public function update(Request $request, Post $post)
10 {
11 $request->validate(['tags' => 'array', 'tags.*' => 'string|max:50']);
12 
13 try {
14 $post->syncTags($request->input('tags', []));
15 } catch (TagPolicyException $exception) {
16 return back()->withErrors(['tags' => $exception->getMessage()]);
17 }
18 
19 return redirect()->route('posts.show', $post);
20 }
21}
resources/views/posts/show.blade.php
1@foreach ($post->tags as $tag)
2 <a href="{{ route('tags.show', $tag->slug) }}">#{{ $tag->name }}</a>
3@endforeach

#2. Autocomplete endpoint

routes/web.php
1use Illuminate\Http\Request;
2use Pharaonic\Laravel\Tags\Models\Tag;
3 
4Route::get('/tags/suggest', function (Request $request) {
5 return Tag::suggest((string) $request->query('q', ''), 8)
6 ->map(fn (Tag $tag) => ['name' => $tag->name, 'slug' => $tag->slug]);
7});

GET /tags/suggest?q=lar answers 200 with JSON such as [{"name":"Laravel","slug":"laravel"},{"name":"Larastan","slug":"larastan"}].

#3. Faceted filters with typed tags

withAllTags([]) keeps every model, but withAnyTags([]) matches none, so add the level filter only when it is set:

app/Http/Controllers/CourseController.php
1use App\Models\Course;
2 
3$query = Course::query()->withAllTags($request->input('topics', []), 'topic');
4 
5if ($request->filled('levels')) {
6 $query->withAnyTags($request->input('levels'), 'level');
7}
8 
9$courses = $query->with('tags')->paginate();

#4. Cleaning up duplicates

app/Console/Commands/MergeTags.php
1use Pharaonic\Laravel\Tags\Models\Tag;
2 
3$duplicates = ['js' => 'JavaScript', 'ts' => 'TypeScript'];
4 
5foreach ($duplicates as $from => $into) {
6 $source = Tag::findByName($from);
7 $target = Tag::findByName($into);
8 
9 if ($source && $target && ! $source->is($target)) {
10 $source->mergeInto($target, true); // "js" keeps working as an alias
11 }
12}
app/Http/Controllers/PostController.php
1use Pharaonic\Laravel\Tags\Models\Tag;
2 
3$related = $post->relatedModels(Tag::ANY_TYPE, true)
4 ->where('published', true)
5 ->limit(4)
6 ->get();
7 
8foreach ($related as $item) {
9 $item->shared_tags_count; // e.g. 3
10 $item->similarity; // e.g. 0.6
11}

#Troubleshooting

#"The table [tags] already exists"

The migrations refuse to run over existing tags or taggables tables, which pharaonic/laravel-taggable and spatie/laravel-tags also use. Rename the old tables first (see the Upgrade Guide), or set other names in pharaonic.tags.tables.

#The same name gives a second tag

Names are the same tag only within one type: php untyped and php of type language are two tags. Check the type you pass. Names are compared after normalization (case, width, spacing), so PHP, php and php are one tag, while php7 and php 7 are two, and so are cafe and café: accents and diacritics count, on every database.

#detachTag() or hasTag() finds a tag of another type

Reads, detach, sync and clear take every type when the type is omitted. Pass null for untyped tags only, or the type:

1$post->detachTag('php', null); // untyped only
2$post->detachTag('php', 'language'); // that type only

#"The tag key [...] is not an integer"

Integers are tag keys and strings are names; tags with UUID or ULID keys must be given as Tag models. A numeric string such as '42' is a name.

#"The morph type of [...] is longer than 191 characters"

Register a short alias with Relation::morphMap(); see Key Types and Morph Maps.

#A TagPolicyException on attach

A name has no tag and auto_create is off for the model. Attach existing tags only, or turn auto_create on. See Policies.

#"The tags changed while this operation ran"

A RetryableWriteException reached your code. The package runs a write again after a lost race only when it opened the transaction; inside your own DB::transaction() the error goes to you. Catch it and run your whole transaction again; DB::transaction($callback, $attempts) does not retry it, because Laravel retries only the deadlocks it recognizes.

#Events are not dispatched

Package events are dispatched after the outermost commit on the tags connection, and dropped on a rollback. Check that pharaonic.tags.events is true and that the code does not run inside Tag::withoutTagEvents(). In tests that wrap each test in a transaction, see Events.

#Taggings of deleted models remain

Mass deletes (Post::query()->delete()) fire no model events, so their taggings stay. Run php artisan tags:prune --orphans --apply, for example from the scheduler.

#Upgrade Guide

This is the first release of pharaonic/laravel-tags, so a new installation needs no upgrade steps. It replaces pharaonic/laravel-taggable, and the tables below map the code of both pharaonic/laravel-taggable and spatie/laravel-tags to this package.

The data is not imported. Both packages use the tables tags and taggables, which this package also creates: rename or drop the old tables before running the migrations, or set other names in pharaonic.tags.tables.

#From pharaonic/laravel-taggable

laravel-taggablelaravel-tags
use Pharaonic\Laravel\Taggable\Traits\Taggable;use Pharaonic\Laravel\Tags\Concerns\HasTags;
$post->tag($tags)$post->attachTags($tags)
$post->detag($tags)$post->detachTags($tags)
$post->syncTags($tags)$post->syncTags($tags)
$post->tags$post->tags
Tag::popular()Tag::popular()
config('Pharaonic.taggable.children') relations$tag->models(Post::class)
Tag models and keys onlyNames too: $post->attachTags(['php', 'laravel'])

The new methods return values (the tags, counts or changes) instead of the model, so calls cannot be chained. Tag names are no longer translated by default; a custom tag model can translate names (see Translations).

#From spatie/laravel-tags

spatie/laravel-tagslaravel-tags
use Spatie\Tags\HasTags;use Pharaonic\Laravel\Tags\Concerns\HasTags;
attachTag(), attachTags(), detachTag(), detachTags(), syncTags()Same names
syncTagsWithType($tags, $type)syncTags($tags, $type)
tagsWithType($type)tagsOfType($type)
hasTag($tag, $type)hasTag($tag, $type)
withAnyTags(), withAllTags(), withoutTags()Same names
withAnyTagsOfAnyType($tags), withAllTagsOfAnyType($tags)withAnyTags($tags), withAllTags($tags)
Tag::findOrCreate($name, $type)Tag::findOrCreate($name, $type) (one name; Tag::bulkCreate() for many)
Tag::findFromString($name, $type)Tag::findByName($name, $type)
Tag::withType($type), Tag::getWithType($type)Tag::ofType($type), Tag::ofType($type)->get()
Tag::containing($term)Tag::search($term)
Tag::ordered()Tag::ordered()
$post->tags = [...]$post->syncTags([...])

Two behaviors differ:

  • Omitted types. spatie treats an omitted type as untyped tags only in detach and in withAnyTags() and withAllTags(). Here reads, detach, sync and clear take every type; pass null to keep the old meaning.
  • Return values. The write methods return the tags, a count or the changes, not the model.

Contributors

Amazing people who made this package possible

This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Laravel Tags!

Moamen Eltouny

@MoamenEltouny

39 contributions

Want to Contribute?

We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.

Was this page helpful?

Something wrong or missing? Report it on GitHub .