# Laravel Tags documentation (v13.x)

> Canonical: https://pharaonic.dev/packages/laravel/tags/13.x  
> Version: v13.x (latest release 13.0.0, 2026-12-06)  
> Install: composer require pharaonic/laravel-tags  
> Requires: PHP 8.3 – 8.6, Laravel 13  
> Repository: https://github.com/Pharaonic/laravel-tags  
> All versions: https://pharaonic.dev/packages/laravel/tags/13.x.md https://pharaonic.dev/packages/laravel/tags/12.x.md https://pharaonic.dev/packages/laravel/tags/11.x.md https://pharaonic.dev/packages/laravel/tags/10.x.md https://pharaonic.dev/packages/laravel/tags/9.x.md https://pharaonic.dev/packages/laravel/tags/8.x.md https://pharaonic.dev/packages/laravel/tags/7.x.md https://pharaonic.dev/packages/laravel/tags/6.x.md

:::badges
- Laravel Package {color=blue}
- v13.0.0 {color=green}
- MIT License {color=purple}
- AI Ready {color=violet}
:::

# 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.

:::success AI Ready
Laravel Tags ships Laravel Boost resources: a guideline loaded in every session and a `tags-development` skill loaded when your agent works on tags. Run `php artisan boost:install` and Claude Code, Cursor, Codex, Copilot or Gemini CLI write correct tagging code. See [AI Ready](#ai-ready).
:::

:::features
### 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.

:::

:::info 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.3, 8.4, 8.5 or 8.6
- Laravel 13.x
- `pharaonic/laravel-sluggable` (installed with the package) for tag slugs
- Optional: `pharaonic/laravel-translatable` to translate tag names

### Composer Installation

```bash title="Terminal" no-line-numbers
composer require pharaonic/laravel-tags
```

The service provider is registered automatically.

### Run Migrations

```bash title="Terminal" no-line-numbers
php artisan migrate
```

The 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 |

:::warning 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](#upgrade-guide)), or set other table names in the configuration.
:::

### Publish Files

Publish only what you need to change:

```bash title="Terminal" no-line-numbers
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.

:::success 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).

| 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. |

```php title="config/pharaonic/tags.php"
return [
    // ...
    'key_type' => 'string',

    'policy' => [
        'auto_create' => false,
    ],
];
```

:::warning 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.

```php title="app/Models/Post.php"
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Pharaonic\Laravel\Tags\Concerns\HasTags;

class Post extends Model
{
    use HasTags;
}
```

### 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).

```php
use Pharaonic\Laravel\Tags\Models\Tag;

$post->attachTags(['Laravel', 'PHP']);   // Collection of the two tags
$post->attachTag('laravel');             // the same Laravel tag: it stays where it is
$post->attachTag(Tag::findOrCreate('Pest'));

$post->detachTag('php');                 // true: the post had it
$post->detachTags(['pest', 'unknown']);  // 1: how many the post lost

$result = $post->syncTags(['Laravel', 'Livewire']);
$result['attached']->pluck('name');      // ["Livewire"]
$result['detached'];                     // tags the post lost
$result['updated'];                      // tags whose metadata changed

$post->clearTags();                      // how many it lost
```

### Read tags

```php
$post->tags;                             // in the post's order, with pivot position and metadata
$post->hasTag('LARAVEL');                // true
$post->hasAnyTags(['vue', 'livewire']);  // true
$post->hasAllTags(['laravel', 'vue']);   // false

Post::with('tags')->get();               // eager loading
Post::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.

```php
$post->attachTag('Laravel');               // untyped
$post->attachTag('Laravel', 'framework');  // another tag, of the type "framework"

$post->tagsOfType('framework');            // from the loaded relation
$post->tagsOfType(null);                   // the untyped tags
```

The 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:

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.

```php
$tag = Tag::findOrCreate('  Café   Society ');
$tag->name;                                 // "Café Society"

Tag::findByName('CAFÉ SOCIETY');            // the same tag
Tag::findOrCreate('Straße');
Tag::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`.

```php title="app/Tags/HashtagNormalizer.php"
namespace App\Tags;

use Pharaonic\Laravel\Tags\Contracts\TagNormalizer;
use Pharaonic\Laravel\Tags\Support\TagNameNormalizer;

class HashtagNormalizer implements TagNormalizer
{
    public function display(string $name): string
    {
        return ltrim((new TagNameNormalizer)->display($name), '#');
    }

    public function normalize(string $name): string
    {
        return (new TagNameNormalizer)->normalize($this->display($name));
    }
}
```

### 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

```php
$tag->rename('Laravel Framework');          // the old name is forgotten
$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.

```php
$tag = Tag::findOrCreate('JavaScript');
$tag->addAlias('JS');                       // TagName
$tag->addAlias('ecmascript', 'en');         // an alias with a locale

$post->attachTag('js');                     // the JavaScript tag
Tag::findByName('ECMAScript');              // the JavaScript tag

$tag->aliases;                              // TagName models, by normalized name
$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.

```php
$source = Tag::findByName('js');
$target = Tag::findByName('JavaScript');

$source->mergeInto($target);                // the target, refreshed
$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:

```php title="app/Models/Article.php"
use Illuminate\Database\Eloquent\Model;
use Pharaonic\Laravel\Tags\Concerns\HasTags;

class Article extends Model
{
    use HasTags;

    public function autoCreatesTags(): bool
    {
        return false;
    }
}
```

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

```php
use Pharaonic\Laravel\Tags\Exceptions\TagPolicyException;

try {
    $article->attachTags(['Laravel', 'Something new']);
} catch (TagPolicyException $exception) {
    $exception->getMessage();   // "The tags [Something new] do not exist, ..."
}
```

`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.

```php
$post->attachTag('Laravel', null, ['weight' => 3, 'source' => 'editor']);

$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:

```php
Tag::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.

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

### The global order

```php
Tag::reorder([$php, $laravel]);             // positions 1, 2 (models or integer keys)
Tag::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).

```php
Post::withAnyTags(['laravel', 'php'])->get();      // at least one
Post::withAllTags(['laravel', 'php'])->get();      // every one
Post::withoutTags(['draft'])->get();               // none of them
Post::withoutAnyTags()->get();                     // no tag at all
Post::withoutAnyTags('topic')->get();              // no tag of the type
Post::withTagsCount()->get();                      // a tags_count column
Post::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

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

### Tagged models of a tag

```php
$tag->models(Post::class)->latest()->paginate();
$tag->taggables()->count();
```

## Search and Related

### Search

`search` matches tags whose name, translation, alias or slug contains the term, exact names first, then names that start with it, then by name.

```php
Tag::query()->search('lara')->get();
Tag::query()->search('lara', 'topic')->get();          // in one type
Tag::query()->search('برم', Tag::ANY_TYPE, 'ar')->get(); // names in one locale, plus aliases
```

The term is normalized like a name, and `%` and `_` in it are literal characters.

### Suggestions

`Tag::suggest()` returns tags with a name, translation or alias that starts with the term: exact names first, then the most used, then by name.

```php
Tag::suggest('lar');                         // up to 10
Tag::suggest('lar', 5, 'topic', 'en');       // limit, type, locale
```

### Related tags

Tags that share models with a tag, with a `cooccurrences` column, the most shared first.

```php
$tag->related()->limit(10)->get();
$tag->related(Post::class)->get();           // through posts only
```

### Related models

Models of the same class that share tags with a model, with a `shared_tags_count` column. With `true`, a `similarity` column (the Jaccard index: shared tags divided by the tags either model has) orders them first.

```php
$post->relatedModels()->limit(5)->get();
$post->relatedModels('topic')->get();                    // through topic tags only
$post->relatedModels(Tag::ANY_TYPE, true)->limit(5)->get();
```

Both return query builders, so you can add constraints, eager loads and pagination.

## Bulk Operations

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

```php
use Pharaonic\Laravel\Tags\Models\Tag;

Tag::bulkCreate(['Laravel', 'PHP', 'laravel']);         // 2 tags, in order, no duplicates

Tag::bulkAttach($posts, ['featured']);                  // taggings created
Tag::bulkDetach($posts, ['draft']);                     // taggings removed

$result = Tag::bulkSync($posts, ['news', 'laravel']);
$result['attached'];                                    // counts
$result['detached'];
$result['updated'];
$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.

:::warning 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.

```bash title="Terminal" no-line-numbers
composer require pharaonic/laravel-translatable
```

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

```php title="app/Models/Tag.php"
namespace App\Models;

use Pharaonic\Laravel\Tags\Models\Tag as BaseTag;
use Pharaonic\Laravel\Translatable\Translatable;

class Tag extends BaseTag
{
    use Translatable;

    protected $translatables = ['name'];

    public function getTranslatableModel()
    {
        return TagTranslation::class;
    }

    public function getTranslatableField()
    {
        return 'tag_id';
    }
}
```

```php title="app/Models/TagTranslation.php"
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class TagTranslation extends Model
{
    public $timestamps = false;

    protected $guarded = [];
}
```

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

```php title="config/pharaonic/tags.php"
'models' => [
    'tag' => App\Models\Tag::class,
    // ...
],
```

### Using translated tags

```php
$tag = new App\Models\Tag;
$tag->setTranslation('name', 'en', 'Programming');
$tag->setTranslation('name', 'ar', 'برمجة');
$tag->save();

Tag::findByName('برمجة');                    // the same tag
app()->setLocale('ar');
$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.

| 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.

```php title="app/Providers/EventServiceProvider.php"
use App\Listeners\RefreshTagCloud;
use Pharaonic\Laravel\Tags\Events\TagsAttached;
use Pharaonic\Laravel\Tags\Events\TagsDetached;

protected $listen = [
    TagsAttached::class => [RefreshTagCloud::class],
    TagsDetached::class => [RefreshTagCloud::class],
];
```

### Turning events off

```php
Tag::withoutTagEvents(function () use ($posts) {
    Tag::bulkAttach($posts, ['imported']);
});
```

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.

:::tip 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.

```bash title="Terminal" no-line-numbers
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_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:

```php title="app/Providers/AppServiceProvider.php"
use Illuminate\Database\Eloquent\Relations\Relation;

Relation::morphMap([
    'post' => App\Models\Post::class,
]);
```

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:

```php title="app/Models/Tag.php"
namespace App\Models;

use Pharaonic\Laravel\Tags\Models\Tag as BaseTag;

class Tag extends BaseTag
{
    public function getUrlAttribute(): string
    {
        return url('/tags/'.$this->slug);
    }
}
```

```php title="config/pharaonic/tags.php"
'models' => ['tag' => App\Models\Tag::class],
'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:

```php
use Illuminate\Support\Facades\DB;

DB::transaction(function () use ($post) {
    $post->syncTags(['laravel', 'php']);
    $post->update(['tagged_at' => now()]);
}, 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.

## AI Ready

Laravel Tags is AI ready. It ships [Laravel Boost](https://laravel.com/docs/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:

```bash title="Terminal" no-line-numbers
php artisan boost:install
```

Boost 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:

```bash title="Terminal" no-line-numbers
php artisan boost:update
```

Requirements: Boost 2 (Laravel 11.45.3 or later, PHP 8.2+) installs the guideline and the skill; Boost 1 installs 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 |

:::tip Keep Them Current
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](#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

- ===Controller

  ```php title="app/Http/Controllers/PostController.php"
  namespace App\Http\Controllers;

  use App\Models\Post;
  use Illuminate\Http\Request;
  use Pharaonic\Laravel\Tags\Exceptions\TagPolicyException;

  class PostController extends Controller
  {
      public function update(Request $request, Post $post)
      {
          $request->validate(['tags' => 'array', 'tags.*' => 'string|max:50']);

          try {
              $post->syncTags($request->input('tags', []));
          } catch (TagPolicyException $exception) {
              return back()->withErrors(['tags' => $exception->getMessage()]);
          }

          return redirect()->route('posts.show', $post);
      }
  }
  ```

- ===Blade View

  ```blade title="resources/views/posts/show.blade.php"
  @foreach ($post->tags as $tag)
      <a href="{{ route('tags.show', $tag->slug) }}">#{{ $tag->name }}</a>
  @endforeach
  ```

### 2. Autocomplete endpoint

```php title="routes/web.php"
use Illuminate\Http\Request;
use Pharaonic\Laravel\Tags\Models\Tag;

Route::get('/tags/suggest', function (Request $request) {
    return Tag::suggest((string) $request->query('q', ''), 8)
        ->map(fn (Tag $tag) => ['name' => $tag->name, 'slug' => $tag->slug]);
});
```

`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:

```php title="app/Http/Controllers/CourseController.php"
use App\Models\Course;

$query = Course::query()->withAllTags($request->input('topics', []), 'topic');

if ($request->filled('levels')) {
    $query->withAnyTags($request->input('levels'), 'level');
}

$courses = $query->with('tags')->paginate();
```

### 4. Cleaning up duplicates

```php title="app/Console/Commands/MergeTags.php"
use Pharaonic\Laravel\Tags\Models\Tag;

$duplicates = ['js' => 'JavaScript', 'ts' => 'TypeScript'];

foreach ($duplicates as $from => $into) {
    $source = Tag::findByName($from);
    $target = Tag::findByName($into);

    if ($source && $target && ! $source->is($target)) {
        $source->mergeInto($target, true);   // "js" keeps working as an alias
    }
}
```

### 5. Related posts with a similarity score

```php title="app/Http/Controllers/PostController.php"
use Pharaonic\Laravel\Tags\Models\Tag;

$related = $post->relatedModels(Tag::ANY_TYPE, true)
    ->where('published', true)
    ->limit(4)
    ->get();

foreach ($related as $item) {
    $item->shared_tags_count;   // e.g. 3
    $item->similarity;          // e.g. 0.6
}
```

## 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](#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:

```php
$post->detachTag('php', null);        // untyped only
$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](#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](#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](#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](#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()` 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.
