Laravel 10 Bootstrap Tags System Example Tutorial

Last Updated on by in Laravel

Laravel Tags system tutorial. In this comprehensive guide, you will learn how to create a tag system in the Laravel application using the laravel-tagging package.

Not only but also, we will bit by bit explain how to build a robust tagging system in laravel application from scratch.

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

Tags are related keywords correlated with or assigned to a piece of information. Tags are usually used on social websites, personal, and blog websites; if you are building any of the sites, you have to implement the tags system in your application.

If you have ever used a wordpress blogging system, you must have seen tagging is the common built-in feature.

Laravel 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 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 have explained how to generate tags in the laravel application. To build the dynamic tags system, we used the laravel-tagging plugin using the composer command-line tool.

We kept the laravel tags example subtle and simple. Your users will now have the freedom to select the tags as this feature allows users to search the data instantly.