Tags(Eloquent 模型添加標籤功能)

📦 套件介紹:spatie/laravel-tags

spatie/laravel-tags 是一個 Laravel 套件,主要功能是為模型(例如文章、商品、影片等)加入「標籤」功能,並支援多語系、自定義標籤類型、多模型共用與標籤查詢等功能。

🔑 功能總覽

功能 說明
🔖 加入標籤 例如 $post->attachTag('Laravel')
🈵 多語系支援 標籤名稱可依語系切換
📂 自定義標籤類型 colorsskills
🔄 多模型共用 不同模型(如 Post、Product)可共用標籤
🔍 查詢標籤 快速查詢擁有特定標籤的模型資料

🛠️ 安裝與設定

composer require spatie/laravel-tags

php artisan vendor:publish --provider="Spatie\Tags\TagsServiceProvider" --tag="tags-migrations"
php artisan migrate

🧱 建立模型(以 Post 為例)

建立資料表

php artisan make:model Post -m
// database/migrations/xxxx_xx_xx_create_posts_table.php

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content')->nullable();
    $table->timestamps();
});

Post 模型

// app/Models/Post.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Tags\HasTags;

class Post extends Model
{
    use HasTags;

    protected $fillable = ['title', 'content'];
}

🚀 基本使用範例

Controller 建立與顯示

// app/Http/Controllers/PostController.php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
        $post = Post::create([
            'title' => $request->input('title'),
            'content' => $request->input('content'),
        ]);

        // 加上標籤(可為字串或陣列)
        $post->attachTags($request->input('tags')); // 例:['Laravel', 'PHP']

        return response()->json([
            'message' => '文章建立成功',
            'post' => $post,
            'tags' => $post->tags->pluck('name'),
        ]);
    }

    public function show(Post $post)
    {
        return response()->json([
            'post' => $post,
            'tags' => $post->tags->pluck('name'),
        ]);
    }
}

🧩 標籤操作

加入標籤

$post = Post::create(['title' => 'Spatie 套件教學']);

// 單一標籤
$post->attachTag('Laravel');

// 多個標籤
$post->attachTags(['PHP', '教學']);

取得標籤

$post->tags; // 回傳 Tag 的集合

$post->tags->pluck('name'); // 例:['Laravel', 'PHP', '教學']

查詢模型擁有的標籤

// 含有任一標籤
Post::withAnyTags(['Laravel', 'PHP'])->get();

// 同時擁有所有標籤
Post::withAllTags(['Laravel', 'PHP'])->get();

🌍 多語系支援(可選)

config/tags.php 設定檔中啟用翻譯:

'use_translations' => true,

加標籤時指定語系:

$post->attachTag([
    'en' => 'Laravel',
    'zh-TW' => '拉拉貓',
]);

🔧 進階功能:自定義標籤類型(Type)

指定標籤類型

$post->attachTag('紅色', '顏色');
$post->attachTag('大型', '尺寸');

查詢指定類型標籤

$post->tagsWithType('顏色'); // 回傳所有「顏色」類型的標籤

📚 官方文件

請參考最新文件:
👉 https://spatie.be/docs/laravel-tags