How to Build Dynamic Tags System in Laravel 10 with Bootstrap

Last Updated on by in Laravel

In this comprehensive tutorial, we will explore how to implement a Bootstrap Tags system in Laravel 10 using the rtconner/laravel-tagging package.

Developers who wish to add a dynamic tagging feature to their Laravel applications should use this tutorial.

We will walk you through the process of setting up your project, migrating the database, and creating a PostController with an index and store method. We will use the laravel-tagging package to handle the application’s tagging functionality.

By the end of this tutorial, you will have a fully functional Laravel application with a Bootstrap Tags system in place. This feature will enable you to add and manage tags for your posts effortlessly.

Whether you are a beginner or an experienced Laravel developer, this guide will provide you with the knowledge and tools needed to enhance your application with dynamic tags.

Let’s dive in and create a powerful tagging system for your Laravel application!

How to Create Tags System in Laravel 10 Application

  • Step 1: Download Laravel App
  • Step 2: Update Database Details
  • Step 3: Install Laravel Tagging Package
  • Step 4: Add Tagging Service
  • Step 5: Create Post Model and Migration
  • Step 6: Set Up Controller
  • Step 7: Create Routes
  • Step 8: Build Post Blade View
  • Step 9: Run Laravel App

Download Laravel App

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

Run command to create a new Laravel application.

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

Move into the project’s root.

cd laravel-demo

Update Database Details

The database is connected to the app by adding database details 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

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

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

Install Laravel Tagging Package

Next, open the terminal add the command to install the laravel tagging package; this package offers the tag support for Laravel Eloquent models recklessly.

composer require rtconner/laravel-tagging

Add Tagging Service in Laravel

By now you have installed the tagging package, it is just the tip of the iceberg. In the subsequent step, you have to register the tagging plugin into the laravel app.

Without further ado, open the app/config/app.php and register the TaggingServiceProvider class into the providers array.

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

Now, you will have to execute the below command to publish the tagging.php in laravel.

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

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

php artisan migrate

Create Model and Migration

In this step, you have to generate model and migration files. It can be done by using a single command, hence execute the following command.

php artisan make:model Post -m

After running the suggested command, new model and migration files have been generated, and you will add values in these files to create a table in the database.

Update 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, get into the app/database/migrations/create_posts_table.php, and you have to 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, you have to execute a command to run migrations.

php artisan migrate

Set Up Controller

A controller is a single class in which you conjugate significant functions to perform a various tasks.

Let’s generate a new controller with the help of the following command.

php artisan make:controller PostController

Further, 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.');
    }
}

Create Routes

Next, add the two routes in the routes/web.php file; these route methods allow 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']);

Build Post Blade View

In the last step, you have to set up the view and integrate the tagging system in laravel using the bootstrap CSS and tag input js.

Open the resources/views folder here; you have to create the index.blade.php file and update the following code into the file.

<!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>

Run Laravel App

In the final step, you need to run the laravel app development server by using the php artisan command.

php artisan serve

Then open the browser and use the url to test the app.

http://127.0.0.1:8000/show-post

How to Create Tags System in Laravel Application

Conclusion

In this tutorial, we successfully set up a Bootstrap Tags system in a Laravel application. By following the provided code and instructions, you can add dynamic tags to your posts effortlessly.

Keep practicing and experimenting with the tagging feature to further improve your Laravel application.

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.