Laravel Tag System Tutorial With Example

Hello developers, In this example, I will show you how to do Laravel Tag System Tutorial.  We use Laravel 5.6 with rtconner/laravel-tagging Package in our application. Bootstrap tags input is a JQuery plugin giving a Twitter Bootstrap user interface for handling tags.

In recent times, tagging systems have become a  most popular way of categorizing items, posts and you can spot them in almost every application. From blog posts to todo lists, they all have tagging implementations. Iy you want to get more information then go to Github.

Laravel Tag System Tutorial With Example

We are going to Configure Laravel Project.

#1: Download Laravel Project

Install fresh Laravel project by the writing following command.

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

#2: Install laravel tagging Package

Now we will install rtconner/laravel-tagging Package in our project.

 composer require rtconner/laravel-tagging "~2.2"

#3: Define Service Provider

Register the service provider in your app.php config file:

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

Then publish the configurations by:

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

#4: Configure SQL Database

Now we can setup database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tagsystem
DB_USERNAME=root
DB_PASSWORD=

#5: Build Model and Migration File

php artisan make:model Post -m

It will create a Post.php file and also create a create_posts_table.php  migration file.

//create_posts_table

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

Add trait in a model file.

//Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use \Conner\Tagging\Taggable;
    protected $fillable = [ 'title', 'body','tags' ];
}

save and run.

php artisan migrate

#6: Create a View File

Create a file in resources  >>  views  >>   createpost.blade.php and put this following code in it.

<!-- createpost.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel Tag System Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">    
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.js"></script>       
  </head>
  <body>
    <div class="container">
    @if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div><br />
@endif
      <h2>Laravel Tag System Tutorial With Example</h2><br/>
      <form method="post" action="{{url('addpost')}}">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Title">Title:</label>
            <input type="text" class="form-control" name="title">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="Body">Body:</label>
              <input type="text" class="form-control" name="body">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="Tags">Tags:</label>
              <input type="text" data-role="tagsinput" class="form-control" name="tags">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Add Post</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

#7: Create one controller

 php artisan make:controller PostController

It will build a controller file called PostController.php.

public function createEvent()
    {
        return view('createpost');
    }

#8: Define Route

We register all route in a web.php file.

Route::get('addpost','PostController@create');
Route::post('addpost','PostController@store');
Route::get('post','PostController@index');

laravel tag system example

#9: Store Data in Database

Now we can add the tag to the database using store() function in PostController.

//PostController.php

use App\Post;

public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'body' => 'required',
            'tags' => 'required',
        ]);

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


    	$post = Post::create($data);
        $post->tag($tags);


        return redirect('post')->with('success','Post created successfully');
    }

#10: Retrieve Data From Database

Here we retrieve a tag from database and display in an Index page. So open a file and copy the code below and paste in PostController().

 public function index()
    {
        $posts = Post::all();
        return view('post',compact('posts'));
    }

Create a file in resources  >>  views  >>   post.blade.php and put this following code in it.

<!-- post.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index Page</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">    
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    
  </head>
  <body>
    <div class="container">
    <br />
    @if (\Session::has('success'))
      <div class="alert alert-success">
        <p>{{ \Session::get('success') }}</p>
      </div><br />
     @endif
   @foreach($posts as $post)
      <h2>{{ $post->title }}</h2>
      <p>{{ $post->body }}</p>
      <div>
				<strong>Tag:</strong>
				@foreach($post->tags as $tag)
					<label class="label label-info">{{ $tag->name }}</label>
				@endforeach
			</div>
      @endforeach
    </div>
  </body>
</html>

laravel tag tutorial

At last, our Laravel Tag System Tutorial With Example is over.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.