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의 보안 기능과 취약점 방지 방법 Laravel은 PHP 프레임워크 중 하나로, 웹 애플리케이션...

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

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

Laravel에서 Import 및 Export 기능을 구현하기

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

Laravel의 Auth 및 Passport의 차이

Laravel은 PHP 웹 애플리케이션 개발을 위한 프레임워크로, 기본적으로 사용자 인증을 쉽게 처리할 수 있도...

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

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

Laravel의 로그 파일을 관리하는 방법은 무엇인가요?

Laravel의 로그 파일 관리 방법 Laravel은 웹 애플리케이션의 구조와 기능을 관리하기 위해 강력...