Add Tags to Articles: Laravel Many-to-Many Relationships with Select2 (ok)

https://blog.quickadminpanel.com/add-tags-to-articles-laravel-many-to-many-relationships-with-select2/

C:\xampp\htdocs\datvietcoconut\database\migrations\2022_12_09_015715_create_articles_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateArticlesTable extends Migration
{
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('articles', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title')->nullable();
      $table->text('article_text')->nullable();
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('articles');
  }
}

C:\xampp\htdocs\datvietcoconut\database\migrations\2022_12_09_015735_create_tags_table.php

C:\xampp\htdocs\datvietcoconut\database\migrations\2022_12_09_015752_create_article_tag_table.php

C:\xampp\htdocs\datvietcoconut\app\Models\Tag.php

C:\xampp\htdocs\datvietcoconut\app\Models\Article.php

C:\xampp\htdocs\datvietcoconut\routes\web.php

C:\xampp\htdocs\datvietcoconut\app\Http\Controllers\Admin\ArticlesController.php

C:\xampp\htdocs\datvietcoconut\resources\views\admin\articles\index.blade.php

C:\xampp\htdocs\datvietcoconut\resources\views\admin\articles\edit.blade.php

C:\xampp\htdocs\datvietcoconut\resources\views\admin\articles\create.blade.php

C:\xampp\htdocs\datvietcoconut\app\Http\Requests\Admin\StoreArticlesRequest.php

C:\xampp\htdocs\datvietcoconut\app\Http\Requests\Admin\UpdateArticlesRequest.php

C:\xampp\htdocs\datvietcoconut\composer.json

Add Tags to Articles: Laravel Many-to-Many Relationships with Select2


Povilas Korop Founder of QuickAdminPanelNovember 26, 2018

This article is a simple example of belongsToMany() relationships in Laravel, with managing the data in CRUD form and table, using Bootstrap framework and Select2 library.

Here’s what we’re building – a list of articles with their tags.

Notice: This example was mostly generated with our QuickAdminPanel generator, but will be explained step-by-step in plain Laravel, so you can use it without our generator.

Step 1. Database/model structure

Here are the migrations.

Articles:

Tags:

Pivot table:

The models are really simple, too.

app/Tag.php:

app/Article.php:


Routes, Controller and Create Form

Our routes/web.php, in addition to Route Group and Middleware, will have this main line:

Now, here’s our (simplified) app/Http/Controllers/Admin/ArticlesController.php:

To add the articles with their tags, we need to have a create form. Here’s our resources/views/admin/articles/create.blade.php:

This is our visual result:

Now, there are quite a few places to explain here:

  1. In this article, I won’t discuss the main layout and code like @extends(‘layouts.app’) and @section(‘content’) because you may have different design and structure, it’s not the subject of this article;

  2. We use LaravelCollective/html package to build the forms with {!! Form::open() !!} and other methods;

  3. See how $tags are passed into the form, we’re getting those values from the Controller, mentioned above;

  4. Above the tags field, we have two buttons: Select all and Deselect all – their behavior in jQuery is implemented in @section(‘javascript’);

  5. We use Select2 library to make the tags searchable and visually compelling.

So here we have our create form.


Saving the data

This part is pretty simple, here’s a method from app/Http/Controllers/Admin/ArticlesController.php:

To validate the data, we use app/Http/Requests/StoreArticlesRequest.php class:

And in the Controller, we just store the article and then use sync() method of many-to-many relationships to store the tags.


Viewing tags in the table

In the screenshot on the top you can see how tags are structured in the table. Here’s our Blade file for this. resources/views/admin/articles/index.blade.php:

This is the most important line – we’re using Bootstrap label classes for styling:


Editing the Article

Here’s Controller code:

And in resources/views/admin/articles/edit.blade.php we show tags this way:

As you can see, we pull in the current value as $article->tag->pluck(‘id’)->toArray().

Updating the data is straightforward, here’s the controller method, really similar to store():


Deleting the data

This is probably the most simple code – here’s Controller method:

But keep in mind that in our migrations files we specified that we need to delete tags on deleting the article, with this rule onDelete(‘cascade’):

Basically, that’s it – a simple demo of many-to-many with Select2 and Bootstrap. If you want it to be generated automatically, try our QuickAdminPanel!

Last updated

Was this helpful?