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에서 Import 및 Export 기능을 구현하기

Laravel은 웹 애플리케이션 개발에 있어 강력한 프레임워크입니다. 데이터의 Import(가져오기) 및 Export(...

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

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

Laravel에서 태스크 자동화를 설정하는 방법

Laravel은 웹 애플리케이션 개발을 위한 강력한 PHP 프레임워크로, 태스크 자동화 기능을 제공합니다....

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

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

Laravel에서 요일마다 실행되는 작업을 스케줄링하는 방법

Laravel은 강력한 스케줄링 기능을 제공하여 개발자가 주기적으로 실행되어야 하는 작업을 쉽게 관리할 수...

Laravel에서 마이그레이션을 롤백하는 방법

Laravel은 데이터베이스 스키마 관리를 용이하게 하기 위해 마이그레이션 기능을 제공합니다. 마이그레이션...