# spatie/laravel-tags architecture

> Architecture diagram of the GitHub repository spatie/laravel-tags, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-02-28). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/spatie/laravel-tags
- Repository: https://github.com/spatie/laravel-tags

## Overview

##### What this project is (type + purpose)
This repo is **a Laravel package/library** (not a standalone app) that adds **taggable behavior** to **any Eloquent model** via a trait. It provides:
- A `Tag` Eloquent model and schema (`tags` + `taggables`)
- A `HasTags` trait that adds relationships + query scopes + attach/detach/sync APIs
- Optional features: **translations** (JSON fields), **tag types**, **sorting/order_column**, **slugs**
- Laravel integration via a **Service Provider** that publishes **migrations** and **config**

##### How to read the file tree (what maps to architecture)
Key architectural anchors in this repo:

##### Laravel integration / bootstrapping
- `src/TagsServiceProvider.php`
- Registers package with Laravel
- Enables publishing:
- `database/migrations/create_tag_tables.php.stub`
- `config/tags.php`

##### Domain model + behavior
- `src/Tag.php`
The core entity: represents a tag (name, slug, type, translations, order).
- `src/HasTags.php`
Trait applied to *host app models* to make them taggable (relationships, scopes, attach/detach/sync).
- `src/HasSlug.php`
Concern for slug generation (driven by `config/tags.php` slugger).

##### Persistence / schema
- `database/migrations/create_tag_tables.php.stub`
Defines:
- `tags` table (includes JSON fields for translatable values; order/sort column)
- `taggables` pivot table for polymorphic many-to-many (tag_id + taggable_id + taggable_type + type, etc.)

##### Configuration
- `config/tags.php`
- `slugger` function override (important “plug-in” point)

##### Quality / verification (useful to infer behavior but not “runtime components”)
- `tests/**` show supported behaviors and extension points (custom tag model, custom locale, translated attributes).

##### Context: where this package sits (inside a host Laravel app)
2) **Container**: the host app runtime containers (App, DB) and the package as an internal library module
3) **Component**: internal package components (ServiceProvider, Trait, Tag model, migrations/config)

You want to make it explicit that the “consumers” are **other Eloquent models**, not an HTTP client.

##### Host Laravel Application (external to this repo, but essential
- **User code / Domain models** (e.g., `NewsItem extends Model`)
- Adds `use HasTags;`
- Calls APIs like `attachTag`, `syncTagsWithType`, `withAnyTags`, etc.
- **Laravel Framework**
- Service container, Eloquent ORM, migrations, config, helpers

##### Spatie Tags Package (this repo)
- **TagsServiceProvider**
- Publishes migration + config
- (Potentially binds/extends tag model depending on config—tests indicate custom tag model support)
- **HasTags trait**
- Adds polymorphic many-to-many relationship to tags (via `taggables`)
- Provides query scopes (`withAnyTags`, `withAllTags`, `withoutTags`, and type-based variants)
- Provides commands: attach/detach/sync, translation helpers like `tagsTranslated()`
- **Tag model**
- Handles find-or-create, translations, slug, sorting/order
- **HasSlug**
- Slug generation based on config `slugger` (or default `Str::slug`)

##### Database (external but central)
- **tags table**
- “Tag definition” records (name/slug may be JSON if translatable)
- type + order_column for multi-type + sorting
- **taggables table**
- Pivot for polymorphic relation:
- `tag_id`
- `taggable_id`
- `taggable_type`
- (and possibly `type` to scope tags by type)

##### External dependencies worth labeling
- **DB engine** requirement: JSON support + MySQL-compatible JSON functions

##### Architectural patterns/principles to explicitly highlight
- **Trait-based composition**: `HasTags` is mixed into any Eloquent model.
- **Polymorphic many-to-many**: `taggables` enables tagging multiple model types without per-model pivot tables.
- **Service Provider pattern**: Laravel package bootstrapping + publishable assets.
- **Config-driven behavior**: slug generation is a pluggable function.
- **Optional concerns layered on core**:
- Translations via JSON fields (and helper methods)
- Types (categorizing tags)
- Sorting via `order_column`

##### Don’t overthink it: split into many components
- Separate `HasTags` vs `Tag` vs `HasSlug` vs `ServiceProvider`
- Separate `tags` table vs `taggables` pivot
- “Any Taggable Model(s)” as a polymorphic target
- Call out translation/type/sorting as feature modules (even if implemented inside the same classes)

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% =========================
    %% Diagram A — C4 Context
    %% =========================
    subgraph A["Diagram A — C4 Context"]
        direction TB

        ActorDev["Developer / App Code"]:::actor

        subgraph AHost["Host Laravel Application (External)"]
            direction TB
            HostApp["Host Laravel App"]:::boundary
            HostModels["Domain Models (Eloquent)\n(e.g., NewsItem, Post)"]:::host
            LaravelFW["Laravel Framework\n(Service Container, Eloquent, Migrations, Config)"]:::framework
        end

        subgraph APkg["Spatie Tags Package (This Repo)"]
            direction TB
            Pkg["Tagging Library Module\n(Spatie Tags)"]:::pkg
        end

        subgraph ADB["Database (External)"]
            direction TB
            DB[("Relational DB\n(JSON support required)")]:::db
        end

        ActorDev -->|"adds use HasTags; calls attach/sync/scopes"| HostModels
        HostModels -->|"in-process usage"| Pkg
        LaravelFW -->|"boots package via ServiceProvider"| Pkg
        Pkg <-->|"Eloquent read/write"| DB
    end

    %% =========================
    %% Diagram B — Container / Module View
    %% =========================
    subgraph B["Diagram B — Container / Module View"]
        direction TB

        subgraph BHost["Host Laravel Application Runtime"]
            direction TB
            AppBoundary["App Boundary"]:::boundary
            AppModels["Taggable Eloquent Models\n(any model can be taggable)"]:::host
            ORM["Eloquent ORM\n(Queries, Relationships, Scopes)"]:::framework

            subgraph BMod["Spatie Tags Module (In-process)"]
                direction TB
                SP["TagsServiceProvider\n(publish assets)"]:::pkg
                HT["HasTags Trait\n(relationships + scopes + attach/detach/sync)"]:::pkg
                TG["Tag Model\n(findOrCreate, translations, type, order)"]:::pkg
                HS["HasSlug Concern\n(config-driven slugging)"]:::pkg
                CFG["Package Config\nslugger override + options"]:::config
                MIG["Migration Stub\n(create tags + taggables tables)"]:::config
            end
        end

        subgraph BDB["Database"]
            direction TB
            TagsTbl[("tags table\n(name/slug JSON if translatable)\n(type, order_column)")]:::db
            TaggablesTbl[("taggables pivot\n(tag_id, taggable_id, taggable_type, type)")]:::db
            OtherTbls[("Taggable tables\n(e.g., news_items, posts, ...)")]:::db
        end

        %% Host app usage
        AppModels -->|"uses trait"| HT
        AppModels -->|"queries via ORM"| ORM

        %% Package internal dependencies
        HT -->|"findOrCreate/attach/sync"| TG
        TG -->|"generates slug via"| HS
        HS -.->|"reads config('tags.slugger')"| CFG

        %% Service provider publishing
        SP -->|"publishes migration"| MIG
        SP -->|"publishes config"| CFG

        %% Persistence interactions
        ORM -->|"SELECT/INSERT/UPDATE"| TagsTbl
        ORM -->|"SELECT/INSERT/DELETE"| TaggablesTbl
        ORM -->|"SELECT/UPDATE"| OtherTbls

        TG <-->|"store tag definitions"| TagsTbl
        HT <-->|"persist pivot rows"| TaggablesTbl
        TaggablesTbl -->|"polymorphic link"| OtherTbls
    end

    %% =========================
    %% Diagram C — Component + Data Model + Extension Points
    %% =========================
    subgraph C["Diagram C — Components + Data Model + Extension Points"]
        direction TB

        subgraph CComp["Package Components"]
            direction TB
            SP2["TagsServiceProvider"]:::pkg
            HT2["HasTags Trait"]:::pkg
            TG2["Tag Model"]:::pkg
            HS2["HasSlug Concern"]:::pkg
            CFG2["config/tags.php"]:::config
            MIG2["create_tag_tables migration stub"]:::config

            Features["Optional Features\n(translations, types, sorting/order_column, slugs)"]:::note
        end

        subgraph CER["ER — Core Tables"]
            direction TB
            TagsER[("tags\nid, name, slug, type,\norder_column, (JSON translations)")]:::db
            TaggablesER[("taggables\nid, tag_id, taggable_id,\ntaggable_type, type")]:::db
            AnyModelER["Any Taggable Eloquent Model\n(polymorphic target)"]:::host
        end

        subgraph CExt["Extension Points (Optional Overrides)"]
            direction TB
            CustomSlugger["Custom slugger callable\n(via config)"]:::ext
            CustomTagModel["Custom Tag model\n(swap/extend Tag)"]:::ext
            CustomLocale["Custom locale / translated attrs\n(static locale behaviors)"]:::ext
        end

        %% Component relations
        SP2 -->|"publishes"| MIG2
        SP2 -->|"publishes"| CFG2
        HT2 -->|"calls findOrCreate / attach / detach / sync"| TG2
        TG2 -->|"uses"| HS2
        HS2 -.->|"reads slugger"| CFG2
        Features --- HT2
        Features --- TG2
        Features --- HS2

        %% ER relations
        TG2 <-->|"CRUD tag definitions"| TagsER
        HT2 <-->|"writes/reads pivot rows"| TaggablesER
        TagsER -->|"1..* via tag_id"| TaggablesER
        TaggablesER -->|"*..1 polymorphic\n(tag_id + taggable_id + taggable_type)"| AnyModelER

        %% Extension relations
        CFG2 -.->|"override"| CustomSlugger
        TG2 -.->|"can be replaced by"| CustomTagModel
        TG2 -.->|"uses locale/translations"| CustomLocale
    end

    %% =========================
    %% Flow 1 — Create/Attach/Sync Tags (Sequence as Flow)
    %% =========================
    subgraph S1["Flow 1 — Create/Attach/Sync Tags"]
        direction TB
        S1_AC["App Code (Model)"]:::host
        S1_HT["HasTags Trait"]:::pkg
        S1_TM["Tag Model"]:::pkg
        S1_DB["Database"]:::db

        S1_AC -->|"create()/attachTag()/syncTagsWithType()"| S1_HT
        S1_HT -->|"findOrCreate(tagNames,type,locale)"| S1_TM
        S1_TM -->|"SELECT tags WHERE name/slug/type"| S1_DB
        S1_MISSING{"Missing tags?"}:::note
        S1_DB --> S1_MISSING
        S1_MISSING -->|"yes"| S1_INS["INSERT INTO tags (...)"]:::db
        S1_INS --> S1_DB
        S1_MISSING -->|"no"| S1_PIV["INSERT/DELETE taggables pivot rows"]:::db
        S1_DB --> S1_PIV
        S1_PIV --> S1_DB
        S1_DB -->|"model saved with tags"| S1_AC
    end

    %% =========================
    %% Flow 2 — Querying by Tags (Sequence as Flow)
    %% =========================
    subgraph S2["Flow 2 — Querying by Tags"]
        direction TB
        S2_AQ["App Code (Query)"]:::host
        S2_HTQ["HasTags Scopes"]:::pkg
        S2_ORM["Eloquent ORM"]:::framework
        S2_DBQ["Database"]:::db

        S2_AQ -->|"withAnyTags([...]) / withAllTags([...])"| S2_HTQ
        S2_HTQ -->|"add joins/where on taggables+tags"| S2_ORM
        S2_ORM -->|"SELECT ... JOIN taggables JOIN tags WHERE ..."| S2_DBQ
        S2_DBQ -->|"collection of matching models"| S2_AQ
    end

    %% =========================
    %% Click Events (from component_mapping)
    %% =========================
    click SP "https://github.com/spatie/laravel-tags/blob/main/src/TagsServiceProvider.php"
    click SP2 "https://github.com/spatie/laravel-tags/blob/main/src/TagsServiceProvider.php"
    click HT "https://github.com/spatie/laravel-tags/blob/main/src/HasTags.php"
    click HT2 "https://github.com/spatie/laravel-tags/blob/main/src/HasTags.php"
    click TG "https://github.com/spatie/laravel-tags/blob/main/src/Tag.php"
    click TG2 "https://github.com/spatie/laravel-tags/blob/main/src/Tag.php"
    click HS "https://github.com/spatie/laravel-tags/blob/main/src/HasSlug.php"
    click HS2 "https://github.com/spatie/laravel-tags/blob/main/src/HasSlug.php"
    click CFG "https://github.com/spatie/laravel-tags/blob/main/config/tags.php"
    click CFG2 "https://github.com/spatie/laravel-tags/blob/main/config/tags.php"
    click MIG "https://github.com/spatie/laravel-tags/blob/main/database/migrations/create_tag_tables.php.stub"
    click MIG2 "https://github.com/spatie/laravel-tags/blob/main/database/migrations/create_tag_tables.php.stub"

    click CustomTagModel "https://github.com/spatie/laravel-tags/blob/main/tests/TestClasses/TestCustomTagModel.php"
    click CustomLocale "https://github.com/spatie/laravel-tags/blob/main/tests/TestClasses/TestCustomTagStaticLocaleModel.php"
    click AppModels "https://github.com/spatie/laravel-tags/blob/main/tests/TestClasses/TestModel.php"
    click AnyModelER "https://github.com/spatie/laravel-tags/blob/main/tests/TestClasses/TestAnotherModel.php"
    click OtherTbls "https://github.com/spatie/laravel-tags/tree/main/tests/"
    click Features "https://github.com/spatie/laravel-tags/tree/main/tests/"
    click HostModels "https://github.com/spatie/laravel-tags/tree/main/tests/"

    %% =========================
    %% Styles
    %% =========================
    classDef actor fill:#111827,stroke:#0b1220,color:#ffffff,stroke-width:1px
    classDef boundary fill:#e5e7eb,stroke:#6b7280,color:#111827,stroke-width:1px
    classDef framework fill:#dbeafe,stroke:#2563eb,color:#0b1b3a,stroke-width:1px
    classDef pkg fill:#bfdbfe,stroke:#1d4ed8,color:#0b1b3a,stroke-width:1px
    classDef host fill:#c7d2fe,stroke:#4338ca,color:#111827,stroke-width:1px
    classDef db fill:#bbf7d0,stroke:#16a34a,color:#052e12,stroke-width:1px
    classDef config fill:#fde68a,stroke:#b45309,color:#3b2200,stroke-width:1px
    classDef ext fill:#e9d5ff,stroke:#7c3aed,color:#1f093a,stroke-width:2px,stroke-dasharray: 6 4
    classDef note fill:#fff7ed,stroke:#ea580c,color:#431407,stroke-width:1px,stroke-dasharray: 3 3
```
