Many to many

Tagging is a popular way of categorizing posts in any blog or news related sites. Tag helps for easy maintenance of posts for end users, provides grouping and search capability. This post will help you to multiple tags to your post using Many-to-Many relationship.

Prerequisites:

1.  Laravel

https://laravel.com/docs/5.4#installation

2.  Laravel collective/html:

https://laravelcollective.com/docs/master/html#installation

Step 1:

Add new routes to for post and tag: routes/web.php.
 

//Post
Route::get('post', 'PostController@index');
Route::post('post', 'PostController@store');

//Tag
Route::get('tag', 'TagController@index');
Route::post('tag', 'TagController@store');

 

Step 2: 

Create migration:

We will create three migration files for Post, Tag and Post-Tag.

Tag Migration:

In your console: php artisan make:migration create_tag_table
 

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

class CreateTagTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tag', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tag');
    }
}

 

 

Post Migration:

In your console: php artisan make:migration create_post_table

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

class CreatePostTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('post', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('post');
    }
}

 

Post  Tag Migration:

In your console: php artisan make:migration create_post_tag_table
Post tag table will have post_id and tag_id with refrence from post and tag table respectively.


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

class CreatePostTagTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('post_tag', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->unsigned();
            $table->integer('tag_id')->unsigned();
            $table->foreign('post_id')->references('id')->on('post')->onDelete('cascade');
            $table->foreign('tag_id')->references('id')->on('tag')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('post_tag');
    }
}

 


Step 3:

Create model:

We will now create two model files for Post and Tag. We will also define relation between tag-post and vice versa in their model

  1. Post Model:
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Post extends Model
    {
        protected $table = 'post';
        public $timestamps = true;
    
        protected $fillable = [
           'title',
            'description'
        ];
    
        public function tags()
        {
            return $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');
        }
    }

 

 

  1. Tag Model:
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Tag extends Model
    {
        protected $table = 'tag';
        public $timestamps = true;
    
        protected $fillable = [
            'title'
        ];
    
        public function post()
        {
            return $this->belongsToMany('App\Post', 'post_tag', 'tag_id', 'post_id');
        }
    }

 

 

 Step 4:

Create controller:

  1. Tag Controller:  App\Http\Controller\TagController
    In your console: php artisan make:controller TagController

     
    namespace App\Http\Controllers;
    
    use App\Tag;
    use Illuminate\Http\Request;
    
    
    class TagController extends Controller
    {
        public function index()
        {
            $tags = Tag::get();
        	return view('tag', compact('tags'));
        }
    
        public function store(Request $request)
        {
            Tag::create($request->all());
            return redirect('/tag');
        }
    }

 

  1. Post Controller: App\Http\Controller\PostController
    In your console: php artisan make:controller PostController.
    In post controller we will also call on tag model to pluck all tag’s id and name.
    namespace App\Http\Controllers;
    
    use App\Post;
    use App\Tag;
    use Illuminate\Http\Request;
    
    class PostController extends Controller
    {
        public function index()
        {
            $posts = Post::get();
            $tags =  Tag::pluck('title', 'id')->all();
            return view('post', compact('posts', 'tags'));
        }
    
        public function store(Request $request)
        {
            $blog = Post::create($request->all());
            $blog->tags()->sync($request->tags);
            return redirect('/post');
        }
    }


Step 5:

Create View:

  1. Tag View
     
    <html>
    <head>
        <title>
            Tag
        </title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    </head>
    <body>
    <div class="container">
        <div class="col-md-6 col-lg-6">
            <h2>Input new Tag</h2>
            {!! Form::open(['method' => 'tag']) !!}
            <div class="form-group">
                {!! Form::label('title', 'Title') !!}
                {!! Form::text('title', null, ['class' => 'form-control']) !!}
            </div>
            <div class="form-group">
                {!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
            </div>
            {!! Form::close() !!}
        </div>
        <div class="col-md-6 col-lg-6">
            <h2>Tags</h2>
            <div class="table-responsive">
                <table class="table table-hover">
                    @foreach($tags as $tag)
                        <tr>
                            <td>{{$tag->title}}</td>
                        </tr>
                    @endforeach
                </table>
            </div>
        </div>
    </div>
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </html>
     
  2. Post View: 
     
    <html>
    <head>
        <title>
            Tag
        </title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="///cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
    
    
    </head>
    <body>
    <div class="container">
        <div class="col-md-6 col-lg-6">
            <h2>Input new Post</h2>
            {!! Form::open(['method' => 'post']) !!}
            <div class="form-group">
                {!! Form::label('title', 'Title') !!}
                {!! Form::text('title', null, ['class' => 'form-control']) !!}
            </div>
            <div class="form-group">
                {!! Form::label('description', 'Description') !!}
                {!! Form::textarea('description', null, ['class' => 'form-control']) !!}
            </div>
            <div class="form-group">
                {!! Form::label('tags', 'Tags:') !!}
                {!! Form::select('tags[]',$tags,null,['class' => 'multiple form-control', 'multiple']) !!}
            </div>
            <div class="form-group">
                {!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
            </div>
            {!! Form::close() !!}
        </div>
        <div class="col-md-6 col-lg-6">
            <h2>Tags</h2>
            <div class="table-responsive">
                <table class="table table-hover">
                    @foreach($posts as $post)
                        <tr>
                            <td>{{$post->title}}</td>
                            <td>
                                <ol>
                                    @foreach($post->tags as $tag)
                                        <li>
                                            {{$tag->title}}
                                        </li>
                                    @endforeach
                                </ol>
    
                            </td>
                        </tr>
                    @endforeach
                </table>
            </div>
    
        </div>
    </div>
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    <script>
        $(".multiple").select2();
    </script>
    </html>
     

Related

PHP

Custom form request for Google Recaptcha.

PHP

Increase site speed using Redis as a caching server.

PHP

This article will cover how to deploy a Laravel project in shared hosting.

PHP

Tagging is a popular way of categorizing posts in any blog or news related sites.

keyboard_arrow_up