Laravel Bootstrap Tag System Example Tutorial
Laravel Bootstrap Tag System Example Tutorial

Laravel Bootstrap Tag System Example Tutorial

In this tutorial, we’ll create a simple tag system using Laravel and Bootstrap. Tags are a common feature in many web applications, allowing users to categorize and filter content. We’ll break down the process into easy-to-follow steps, complete with practical code examples.

Step 1: Set Up Laravel Project

First, make sure you have Composer installed. Then, create a new Laravel project:

composer create-project --prefer-dist laravel/laravel tag-system

Navigate to the project directory:

cd tag-system

Step 2: Set Up Database

Configure your database settings in the .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password

Then, run the following command to create the necessary tables:

php artisan migrate

Step 3: Create Models and Migrations

We need two tables: posts and tags. Each post can have multiple tags. Let’s create the models and migrations.

Create the Post model and migration:

php artisan make:model Post -m

Create the Tag model and migration:

php artisan make:model Tag -m

Now, edit the migration files in database/migrations:

Create Posts Table

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

Create Tags Table

public function up()
{
    Schema::create('tags', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
    });
}

Create Post_Tag Pivot Table

We need a pivot table to handle the many-to-many relationship between posts and tags:

php artisan make:migration create_post_tag_table --create=post_tag

Edit the migration file:

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();
    });
}

Run the migrations:

php artisan migrate

Step 4: Define Relationships in Models

Update the Post model to define the relationship with tags:

class Post extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }
}

Update the Tag model to define the relationship with posts:

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

Step 5: Create a Form to Add Posts with Tags

Let’s create a form to add posts with tags. First, install Bootstrap to style the form. Add the Bootstrap CSS link to your resources/views/layouts/app.blade.php file:

<!DOCTYPE html>
<html>
<head>
    <title>Tag System</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        @yield('content')
    </div>
</body>
</html>

Create a view file for the form: resources/views/posts/create.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <h1>Create Post</h1>
    <form method="POST" action="{{ route('posts.store') }}">
        @csrf
        <div class="form-group">
            <label for="title">Title</label>
            <input type="text" class="form-control" id="title" name="title" required>
        </div>
        <div class="form-group">
            <label for="body">Body</label>
            <textarea class="form-control" id="body" name="body" rows="3" required></textarea>
        </div>
        <div class="form-group">
            <label for="tags">Tags</label>
            <input type="text" class="form-control" id="tags" name="tags" placeholder="Comma separated tags">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
</div>
@endsection

Step 6: Handle Form Submission

Add routes to handle the form submission in routes/web.php:

use App\Http\Controllers\PostController;

Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create');
Route::post('/posts', [PostController::class, 'store'])->name('posts.store');

Create the PostController:

php artisan make:controller PostController

Update the PostController to handle the form submission:

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    public function create()
    {
        return view('posts.create');
    }

    public function store(Request $request)
    {
        $post = new Post();
        $post->title = $request->title;
        $post->body = $request->body;
        $post->save();

        $tags = explode(',', $request->tags);
        foreach ($tags as $tagName) {
            $tag = Tag::firstOrCreate(['name' => trim($tagName)]);
            $post->tags()->attach($tag);
        }

        return redirect()->route('posts.create')->with('success', 'Post created successfully.');
    }
}

Step 7: Display Posts with Tags

Let’s create a view to display posts with their tags. Create a new route:

Route::get('/posts', [PostController::class, 'index'])->name('posts.index');

Add the index method to PostController:

public function index()
{
    $posts = Post::with('tags')->get();
    return view('posts.index', compact('posts'));
}

Create the view file: resources/views/posts/index.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <h1>Posts</h1>
    @foreach ($posts as $post)
    <div class="card mb-3">
        <div class="card-body">
            <h5 class="card-title">{{ $post->title }}</h5>
            <p class="card-text">{{ $post->body }}</p>
            <div>
                @foreach ($post->tags as $tag)
                <span class="badge badge-primary">{{ $tag->name }}</span>
                @endforeach
            </div>
        </div>
    </div>
    @endforeach
</div>
@endsection

Conclusion

You’ve now created a simple tag system using Laravel and Bootstrap. Users can add tags to posts, and the tags will be displayed with the posts. This tutorial covered the basics, but you can extend it by adding features like tag management, tag-based search, and more.

Feel free to ask if you have any questions or need further assistance!