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.
Laravel Tags ships Laravel Boost resources: a guideline loaded in every session, which Boost 1 installs on Laravel 10, and a tags-development skill for Boost 2. Run php artisan boost:install and Claude Code, Cursor, Codex, Copilot or Gemini CLI write correct tagging code. See AI Ready.
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.
AI Ready
Laravel Boost guideline and skill included, so php artisan boost:install teaches your coding agent the package.
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.1, 8.2 or 8.3
- Laravel 10.x
pharaonic/laravel-sluggable(installed with the package) for tag slugs- Optional:
pharaonic/laravel-translatableto translate tag names
#Composer Installation
composer require pharaonic/laravel-tagsThe service provider is registered automatically.
#Run Migrations
php artisan migrateThe migrations create three tables:
| Table | Holds |
|---|---|
tags | One row per tag: name, slug, type, position and metadata |
tag_names | Every name a tag answers to: its name, its translations and its aliases, with a unique index on type and normalized name |
taggables | One row per tagged model, with the tagging's position and metadata |
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:
php artisan vendor:publish --tag=tags-configphp artisan vendor:publish --tag=tags-migrationsphp artisan vendor:publish --tag=tags-translationsThe configuration is published to config/pharaonic/tags.php. The laravel-tags tag publishes all three.
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).
| Key | Default | Description |
|---|---|---|
connection | null | The 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.tag | Models\Tag::class | The tag model; a subclass adds behaviour or Laravel Translatable. |
models.tag_name | Models\TagName::class | The model of tag_names. |
models.taggable | Models\Taggable::class | The pivot model of taggables. |
tables.tags / tables.tag_names / tables.taggables | tags / tag_names / taggables | Table names. |
tag_key_type | integer | Keys of tags: integer, uuid (time-ordered version 7) or ulid. |
key_type | integer | Keys of tagged models: integer, uuid, ulid, or string to tag models with different key types in one table. |
events | true | Dispatch the package events. |
normalizer | Support\TagNameNormalizer::class | The 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_create | true | Create tags for unknown names, or refuse them. |
cleanup_on_soft_delete | false | Detach the tags of a soft-deleted model. |
cleanup_on_force_delete | true | Detach the tags of a deleted (or force-deleted) model. |
1return [2 // ...3 'key_type' => 'string',4 5 'policy' => [6 'auto_create' => false,7 ],8];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.
1namespace App\Models;2 3use Illuminate\Database\Eloquent\Model;4use Pharaonic\Laravel\Tags\Concerns\HasTags;5 6class Post extends Model7{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 lost13$result['updated']; // tags whose metadata changed14 15$post->clearTags(); // how many it lost#Read tags
1$post->tags; // in the post's order, with pivot position and metadata2$post->hasTag('LARAVEL'); // true3$post->hasAnyTags(['vue', 'livewire']); // true4$post->hasAllTags(['laravel', 'vue']); // false5 6Post::with('tags')->get(); // eager loading7Post::withAnyTags(['laravel', 'php'])->get();hasTag(), hasAnyTags() and hasAllTags() use the loaded tags relation when it is loaded, and query the database otherwise.
#Input rules
| Given | Means |
|---|---|
'php', '2024' | A name, always; never a key |
5 | The tag with the integer key 5 (integer tag keys only) |
Tag model | That tag; the way to give tags with UUID or ULID keys |
null, floats, arrays inside arrays, blank names | Refused 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'); // untyped2$post->attachTag('Laravel', 'framework'); // another tag, of the type "framework"3 4$post->tagsOfType('framework'); // from the loaded relation5$post->tagsOfType(null); // the untyped tagsThe type argument works the same way everywhere:
| Method | Type omitted | null | 'topic' |
|---|---|---|---|
attachTag(), attachTags(), findOrCreate() | untyped | untyped | the type |
detachTag(s)(), syncTags(), clearTags(), hasTag() and the scopes | every type (Tag::ANY_TYPE) | untyped only | the 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:
- 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.
- 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 tag5Tag::findOrCreate('Straße');6Tag::findByName('STRASSE'); // the Straße tag: full case foldingA 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.
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): string14 {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 forgotten2$tag->rename('Laravel', true); // the old name stays as an aliasRenaming 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'); // TagName3$tag->addAlias('ecmascript', 'en'); // an alias with a locale4 5$post->attachTag('js'); // the JavaScript tag6Tag::findByName('ECMAScript'); // the JavaScript tag7 8$tag->aliases; // TagName models, by normalized name9$tag->removeAlias('js'); // trueAdding 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, refreshed5$source->mergeInto($target, true); // keep the source's names as aliases| What | Happens |
|---|---|
| Models with only the source | Their tagging moves to the target, keeping position and metadata |
| Models with both tags | The target's tagging stays as it is; the source's is dropped |
| Source aliases | Move to the target |
| Source name and translations | Become aliases with true, dropped otherwise |
| Source slug, metadata, position | Dropped 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:
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 one2Post::withAllTags(['laravel', 'php'])->get(); // every one3Post::withoutTags(['draft'])->get(); // none of them4Post::withoutAnyTags()->get(); // no tag at all5Post::withoutAnyTags('topic')->get(); // no tag of the type6Post::withTagsCount()->get(); // a tags_count column7Post::withAnyTags('laravel', 'framework')->get(); // in one typeAn 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 tags2Tag::query()->ordered()->get();3Tag::query()->popular()->limit(10)->get(); // with taggables_count, most used first4Tag::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']; // counts10$result['detached'];11$result['updated'];12$result['changes'][$post->getMorphClass()][$post->getKey()]; // attached, detached and updated collectionschanges 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.
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.
composer require pharaonic/laravel-translatableMake a tag model that translates name with the table strategy, and a model and table for its translations:
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} 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:
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 tag7app()->setLocale('ar');8$post->attachTag('تصميم'); // a new tag, named in ArabicThe 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.
| Event | Properties | Dispatched when |
|---|---|---|
TagCreated | $tag | A tag is created |
TagRenamed | $tag, $previousName | A tag's name changes |
TagDeleted | $tag | A tag is deleted |
TagsMerged | $source, $target, $movedTaggings, $keptNameAsAlias | A tag is merged into another |
TagAliasAdded | $tag, $alias (TagName) | An alias is added (not when it existed) |
TagAliasRemoved | $tag, $alias | An alias is removed |
TagsAttached | $model, $tags | A model gained tags |
TagsDetached | $model, $tags | A model lost tags |
TagsSynced | $model, $attached, $detached, $updated | A sync changed a model's tags |
All events are in the Pharaonic\Laravel\Tags\Events namespace.
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.
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.
php artisan tags:prune # report bothphp artisan tags:prune --orphans --apply # delete orphaned taggings onlyphp artisan tags:prune --unused --apply # delete unused tags onlyphp artisan tags:prune --apply # bothWithout --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_type | Models |
|---|---|
integer | Integer keys (default) |
uuid | UUID keys |
ulid | ULID keys |
string | Any 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:
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:
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}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_nameshas 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.taggableshas 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 transactionThese guarantees are checked by tests that run separate PHP processes at the same moment on MySQL, MariaDB, PostgreSQL and SQLite.
#AI Ready
Laravel Tags is AI ready. It ships Laravel Boost resources, so the coding agent in your application (Claude Code, Cursor, Codex, Copilot, Gemini CLI, Junie…) knows how to use the package.
#Install
With Laravel Boost in your application, run:
php artisan boost:installBoost finds the package's guideline and skill in vendor/ and lists Laravel Tags among the packages to add; choose it and the agents you use. After updating the package, refresh them with:
php artisan boost:updateRequirements: Laravel 10.49 or later with Boost 1 (1.8), which installs the guideline. The skill ships too and is a Boost 2 addition: Boost 2 needs Laravel 11.45.3 or later, so on Laravel 10 your agent gets the guideline only.
#What the Agent Learns
| Resource | Loaded | Covers |
|---|---|---|
Guideline (resources/boost/guidelines/core.blade.php) | In every session | The trait, name identity, types, what the writes return, the policy, querying in SQL, events, and the main writes and queries |
Skill tags-development | When the agent works on tags | Every public method, the configuration, types, aliases and merges, the policy, scopes, search and related content, bulk operations, events, pruning, concurrency and testing |
Add @php artisan boost:update --ansi to your Composer post-update-cmd scripts so the agent always matches the installed release.
#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.
| Method | Description | Returns |
|---|---|---|
tags() | The model's tags in its order, with pivot id, position, metadata | TagsMorphToMany |
tagsOfType(?string $type) | Loaded tags of a type (null for untyped) | Collection |
attachTag($tag, ?string $type = null, ?array $metadata = null) | Attach one tag | Tag |
attachTags($tags, ?string $type = null, ?array $metadata = null) | Attach tags after the others | Collection |
detachTag($tag, ?string $type = '*') | Whether the model had it | bool |
detachTags($tags, ?string $type = '*') | How many the model lost | int |
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 it | bool |
hasAnyTags($tags, ?string $type = '*') | At least one | bool |
hasAllTags($tags, ?string $type = '*') | Every one (true for none) | bool |
reorderTags($tags) | Put these first | void |
relatedModels(?string $type = '*', bool $similarity = false) | Models sharing tags | Builder |
autoCreatesTags() | Whether unknown names create tags; override per model | bool |
scopeWithAnyTags($tags, $type), scopeWithAllTags, scopeWithoutTags | Filter models | — |
scopeWithoutAnyTags(?string $type = '*') | Models without tags | — |
scopeWithTagsCount(?string $type = '*') | Add tags_count | — |
#Tag
| Method | Description | Returns |
|---|---|---|
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 policy | Tag |
Tag::bulkCreate($names, ?string $type = null) | Find or create many | Collection |
Tag::bulkAttach($models, $tags, ?string $type = null, ?array $metadata = null) | Taggings created | int |
Tag::bulkDetach($models, $tags, ?string $type = '*') | Taggings removed | int |
Tag::bulkSync($models, $tags, ?string $type = '*', ?array $metadata = null) | Counts, and changes by morph type and key | array |
Tag::suggest(string $term, int $limit = 10, ?string $type = '*', ?string $locale = null) | Prefix suggestions | Collection |
Tag::reorder($tags) | Global positions 1, 2, … | void |
Tag::withoutTagEvents(callable $callback) | Run without package events | callback result |
rename(string $name, bool $keepOldNameAsAlias = false) | Rename | Tag |
addAlias(string $alias, ?string $locale = null) | Add an alias | TagName |
removeAlias(string $alias) | Whether it had it | bool |
mergeInto(Tag $target, bool $keepNameAsAlias = false) | Merge and delete this tag | Tag (the target) |
deleteIfUnused() | Delete when no model has it | bool |
related(?string $modelClass = null) | Co-occurring tags with cooccurrences | Builder |
models(string $class) | Tagged models of a class | TagsMorphToMany |
names(), aliases(), taggables() | Relations | HasMany |
scopeOfType, scopeOrdered, scopeSearch, scopePopular, scopeUnused | Query scopes | — |
| Property | Description |
|---|---|
name | The canonical name |
slug | The slug |
type | The type, or null |
position | The global position |
metadata | An array, or null |
Tag::ANY_TYPE | '*': every type |
#Exceptions
| Exception | Thrown when |
|---|---|
TagConflictException | A name, alias or translation belongs to another tag |
TagPolicyException | A name has no tag and auto_create is off |
RetryableWriteException | A concurrent write changed what a write read; the package runs it again unless it ran inside your transaction |
InvalidArgumentException | Invalid names, types, keys, metadata or input values |
ModelNotFoundException | A 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
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}1@foreach ($post->tags as $tag)2 <a href="{{ route('tags.show', $tag->slug) }}">#{{ $tag->name }}</a>3@endforeach#2. Autocomplete endpoint
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:
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
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 alias11 }12}#5. Related posts with a similarity score
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. 310 $item->similarity; // e.g. 0.611}#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 only2$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-taggable | laravel-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 only | Names 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-tags | laravel-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()andwithAllTags(). Here reads, detach, sync and clear take every type; passnullto 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!
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?
Thanks, that helps us decide what to improve.
Something wrong or missing? Report it on GitHub .