Laravel 9 Bootstrap Tags System Example

Apr 15, 2022 . Admin

Hi Dev,

This example is how to bootstrap tags system in laravel 9?.

This example is short code and easy way to understand in users.

You will learn how to create a tag system in the Laravel 9 application using the laravel-tagging package.

So let's start following step.

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2: Database Configuration

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

.env
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
Step 3: 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
Step 4: Add Tagging Service config/app.php
....
....
'providers' => [
    ....
    ....

    \Conner\Tagging\Providers\TaggingServiceProvider::class,
    ....
    ....
]
Step 5: Create Publish Tagging Service

below command to publish 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
Step 6: Create Model and Migration
php artisan make:model TagPost -m
app/Models/Post.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class TagPost extends Model
{
    use HasFactory;

    use \Conner\Tagging\Taggable;
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    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.

app/database/migrations/create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tag_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('tag_posts');
    }
}

Consequently, you have to execute a command to run migrations.

php artisan migrate
Step 7: Create Controller

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

php artisan make:controller TagController
app/Http/Controllers/TagController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\TagPost;

class TagController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $tags = TagPost::all();
        return view('tag',compact('tags'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'title_name' => 'required',
            'content' => 'required',
            'tags' => 'required',
        ]);

        $input = $request->all();

        $tags = explode(",", $request->tags);

        $post = TagPost::create($input);

        $post->tag($tags);

        return back()->with('success','Tags added to database.');
    }
}
Step 8: Create Route routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TagController;

/*
|--------------------------------------------------------------------------
| 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-tags', [TagController::class, 'index']);
Route::post('/create-tags', [TagController::class, 'store']);
Step 9: Create Blade File resources/views/tag.blade.php
<!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 9 Tags System Example - Mywebtuts.com</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>
    <div class="container mt-5">
        <h3 class="text-center mb-5">Laravel 9 Tags System Example - Mywebtuts.com</h3>
        <div class="row justify-content-center">
            <div class="col-md-8">
                @if(Session::has('success'))
                    <div class="alert alert-success">
                        {{ Session::get('success') }}
                        @php
                            Session::forget('success');
                        @endphp
                    </div>
                @endif
            
                <form action="{{ url('create-tags') }}" 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 text-white">Submit</button>
                    </div>

                </form>

                <div class="alert alert-success p-1 mt-3 text-center">
                    Tag Collection
                </div>

                @if($tags->count())
                    @foreach($tags as $key => $tag)
                        <h3><strong>Title</strong> : {{ $tag->title_name }}</h3>
                        <p><strong>Content :</strong> {{ $tag->content }}</p>
                        <div>
                            <strong>Tag:</strong>
                            @foreach($tag->tags as $tag)
                                <label class="badge bg-primary">{{ $tag->name }}</label>
                            @endforeach
                        </div>
                    @endforeach
                @endif
            </div>
        </div>
    </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 You need to run the laravel app follow command.
php artisan serve
Open your browser and use the url.
http://localhost:8000/show-tags
Output:

I hope it can help you...

#Laravel 9