How to Create Bootstrap Tags System in Laravel 9 Example Tutorial

This comprehensive guide will help you learn the Bootstrap Tags System in Laravel 9 and create a tag system using the Laravel-tagging package. We will learn on how to build a robust tagging system in Laravel application from scratch.

Let us first understand why tagging is essential; In web applications, tagging befits users by discovering content related to their interests.

Tags are related keywords related to or assigned to your information. Tags usually appear on personal, and blog websites; and social websites. If you are working on any of such sites, you will have to implement a tags system for your application.

If you have used a WordPress blogging system, you must see tagging is a common built-in feature.

Laravel framework doesn’t come with a tag system; therefore, we will show you how to create a simple tag system in Laravel, and it will help you generate tags in Laravel so quickly.

How to Create Tags System in Laravel Application

Step 1: Create a new Laravel App

Assuming you have already downloaded and configured the PHP Composer on your system.

You may now run command to create a new Laravel application.

composer create-project --prefer-dist laravel/laravel laravel-tags

Navigate into the project’s root directory through command line.

cd laravel-tags

Step 2: Update Database Details

The database is connected to the app by adding the database details as shown below into the .env configuration files.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

In case, you are using MAMP local server in macOS; make sure to append DB_SOCKET and UNIX_SOCKET below database credentials in your .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Step 3: Install the Tagging Package

Next, open and type in the terminal the command below to install the Laravel tagging package. It will offer tag support for Laravel Eloquent models.

composer require rtconner/laravel-tagging

Step 4: Add Tagging Service

You have now installed the Laravel tagging package. Next, you will have to register the tagging plugin into the Laravel app.

Open the app/config/app.php file and register the TaggingServiceProvider class into the providers array as shown below.

....
....
'providers' => [
	....
	....
	\Conner\Tagging\Providers\TaggingServiceProvider::class,
	....
	....
]

Now, you execute the command below to publish the tagging.php in Laravel.

php artisan vendor:publish --provider="Conner\Tagging\Providers\TaggingServiceProvider"

Next, you will have to run a command for migration of the tags system, this will generate tagging tables into the database.

php artisan migrate

Step 5: Create Model and Migration

In this step, you will now generate model and migration files. The single command shown below will do this. Hence execute the following command.

php artisan make:model Post -m

This creates a new model and generates new migration, and may now add corresponding values in these files to create a table in the database.

Update the code in app/Models/Post.php file.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    use HasFactory;
    use \Conner\Tagging\Taggable;
    
    protected $fillable = [ 
        'title_name', 
        'content' 
    ];
}

Now, open the app/database/migrations/create_posts_table.php file, and insert the table values into this migration file.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title_name');
            $table->text('content');            
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Consequently, execute the command below to run migrations.

php artisan migrate

Step 6: Set Up Controller

A controller is the class where significant functions can perform various tasks. Let’s generate a new controller using the following command.

php artisan make:controller PostController

Now, you have to open the app/Http/Controllers/PostController.php and update the file with the given code.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    public function index()
    {
    	$posts = Post::all();
        return view('index', compact('posts'));
    }
    public function store(Request $request)
    {
    	$this->validate($request, [
            'title_name' => 'required',
            'content' => 'required',
            'tags' => 'required',
        ]);
    	$input = $request->all();
    	$tags = explode(",", $request->tags);
    	$post = Post::create($input);
    	$post->tag($tags);
        return back()->with('success','Post added to database.');
    }
}

Step 7: Create new Routes

Next, add the two routes in the routes/web.php file; whose functions are defined in the Controller class. These route methods help invoke GET and POST requests.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/show-post', [PostController::class, 'index']);
Route::post('/create-post', [PostController::class, 'store']);

Step 8: Build Post Blade View

Lastly, you may now set up the view and integrate the tagging system in Laravel using the bootstrap CSS and tag input JS.

Navigate to the resources/views folder here; create the index.blade.php file and update it with the following code.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 8 Tags System Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css"
        rel="stylesheet" />
    <style>
        .bootstrap-tagsinput .tag {
            margin-right: 2px;
            color: #ffffff;
            background: #2196f3;
            padding: 3px 7px;
            border-radius: 3px;
        }
        .bootstrap-tagsinput {
            width: 100%;
        }
    </style>
</head>
<body class="bg-dark">
    <div class="container">
        <h1>Add post</h1>

        @if(Session::has('success'))
        <div class="alert alert-success">
            {{ Session::get('success') }}
            @php
            Session::forget('success');
            @endphp
        </div>
        @endif

        <form action="{{ url('create-post') }}" method="POST">
            {{ csrf_field() }}
            <div class="mb-3">
                <input type="text" class="form-control" name="title_name" placeholder="Enter title">
                @if ($errors->has('title_name'))
                <span class="text-danger">{{ $errors->first('<title></title>') }}</span>
                @endif
            </div>

            <div class="mb-3">
                <textarea class="form-control" name="content" placeholder="Enter content"></textarea>
                @if ($errors->has('content'))
                <span class="text-danger">{{ $errors->first('content') }}</span>
                @endif
            </div>

            <div class="mb-3">
                <input class="form-control" type="text" data-role="tagsinput" name="tags">
                @if ($errors->has('tags'))
                <span class="text-danger">{{ $errors->first('tags') }}</span>
                @endif
            </div>

            <div class="d-grid">
                <button class="btn btn-info btn-submit">Submit</button>
            </div>
        </form>

        <div class="alert alert-primary mt-5 text-center">
            Post Collection
        </div>

        @if($posts->count())
        @foreach($posts as $key => $post)
        <h3>{{ $post->title_name }}</h3>
        <p>{{ $post->content }}</p>
        <div>
            <strong>Tag:</strong>
            @foreach($post->tags as $tag)
            <label class="label label-info">{{ $tag->name }}</label>
            @endforeach
        </div>
        @endforeach
        @endif
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.js"></script>
</body>
</html>

Step 9: Run Laravel App

Finally, run the Laravel app development server by using the php artisan command.

php artisan serve

Then open your browser and use the URL below to test your app.

http://127.0.0.1:8000/show-post
How to Create Tags System in Laravel Application

Conclusion

To sum up, the tutorial explains how to generate tags in a Laravel application. To build the dynamic tags system, we used the Laravel-tagging plugin using the composer command-line tool.

The subtle and simple Laravel bootstrap tags system example will help users to have the freedom to select the tags as this feature allows users to search the data instantly.