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() }}
결론
이제 글 작성 시 태그를 추가하고, 태그별로 글을 필터링하여 보여줄 수 있습니다.
태그는 사용자 검색과 주제 분류에 매우 유용하며, 블로그 구조를 더욱 확장 가능하게 만듭니다.