Laravel 블로그에 태그 기능 추가하기

블로그 글에 태그(tag)를 추가하면 글을 주제별로 분류하고 필터링할 수 있어 사용자 경험이 향상됩니다.

Laravel에서 태그 기능을 구현하는 방법을 소개합니다.

1. 태그용 테이블 및 관계 설정

1-1. 마이그레이션 파일 생성

php artisan make:model Tag -m
// database/migrations/xxxx_create_tags_table.php

public function up()
{
    Schema::create('tags', function (Blueprint $table) {
        $table->id();
        $table->string('name')->unique();
        $table->timestamps();
    });
}
// 다대다 중간 테이블
php artisan make:migration create_post_tag_table
// database/migrations/xxxx_create_post_tag_table.php

public function up()
{
    Schema::create('post_tag', function (Blueprint $table) {
        $table->id();
        $table->foreignId('post_id')->constrained()->onDelete('cascade');
        $table->foreignId('tag_id')->constrained()->onDelete('cascade');
        $table->timestamps();
    });
}

그 다음 마이그레이션을 실행합니다.

php artisan migrate

2. 모델 관계 설정

// app/Models/Post.php

public function tags()
{
    return $this->belongsToMany(Tag::class);
}
// app/Models/Tag.php

public function posts()
{
    return $this->belongsToMany(Post::class);
}

3. 컨트롤러에서 태그 저장

글 저장 시 태그를 연결합니다.

// PostController.php

use App\Models\Tag;

public function store(Request $request)
{
    $post = Post::create([
        'title' => $request->title,
        'body' => $request->body,
    ]);

    $tags = collect(explode(',', $request->tags))
        ->map(fn($name) => trim($name))
        ->filter()
        ->map(function ($name) {
            return Tag::firstOrCreate(['name' => $name])->id;
        });

    $post->tags()->sync($tags);

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

4. Blade에서 태그 입력 및 표시

<!-- posts/create.blade.php -->
<label>태그 (쉼표로 구분)</label>
<input type="text" name="tags" value="{{ old('tags') }}">
<!-- posts/show.blade.php -->
<ul>
  @foreach ($post->tags as $tag)
    <li><a href="{{ route('tags.show', $tag->name) }}">#{{ $tag->name }}</a></li>
  @endforeach
</ul>

5. 태그별 글 필터링

// routes/web.php

Route::get('/tags/{tag}', [TagController::class, 'show'])->name('tags.show');
// TagController.php

use App\Models\Tag;

public function show($name)
{
    $tag = Tag::where('name', $name)->firstOrFail();
    $posts = $tag->posts()->latest()->paginate(10);

    return view('tags.show', compact('tag', 'posts'));
}
<!-- tags/show.blade.php -->
<h2>태그: {{ $tag->name }}</h2>

@foreach ($posts as $post)
  <div><a href="{{ route('posts.show', $post) }}">{{ $post->title }}</a></div>
@endforeach

{{ $posts->links() }}

결론

이제 글 작성 시 태그를 추가하고, 태그별로 글을 필터링하여 보여줄 수 있습니다.

태그는 사용자 검색과 주제 분류에 매우 유용하며, 블로그 구조를 더욱 확장 가능하게 만듭니다.

참고

Tags:
Laravel

관련 게시글

Laravel에서 조건부 라우팅을 구현하는 방법

Laravel은 간편하고 직관적인 라우팅 시스템을 제공하여 웹 애플리케이션의 URL과 그에 연결된 처리 로직을...

Laravel에서 시드 데이터베이스와 연결하는 방법

라라벨(Laravel)은 PHP로 작성된 강력한 웹 애플리케이션 프레임워크로, 데이터베이스와의 효율적인 연결...

Laravel의 기능 테스트와 단위 테스트의 차이

Laravel은 PHP 프레임워크로, 웹 애플리케이션 개발에 필요한 다양한 기능을 제공합니다. 그 중에서도 테스...

Laravel에서 하루에 한 번만 글 조회수 증가시키기

방문자가 글을 볼 때마다 조회수가 무조건 올라가면 실제 관심도나 방문 수치를 왜곡할 수 있습니다. 같은...

Laravel에서 비동기 작업을 수행하는 방법

Laravel은 비동기 작업을 간편하게 처리할 수 있는 다양한 기능을 제공합니다. 비동기 작업은 웹 애플리케...

Laravel에서 스코프에 따른 쿼리 최적화는 어떻게 하나요?

Laravel에서 스코프에 따른 쿼리 최적화 Laravel은 PHP 기반의 프레임워크로, 데이터베이스와의...