Create Many-To-Many Relationship

PHOTO EMBED

Fri Jul 30 2021 00:28:21 GMT+0000 (Coordinated Universal Time)

Saved by @slendabilt #php #laravel

// convention is to make table name singular and in alphabetical order
php artisan make:migration create_post_tag_table

// create_post_tag_table.php
// if 1 post has 5 tags, then 5 records will exist with same post_id and different tag_ids
public function up()
{
  Schema::create('post_tag', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->integer('post_id');
    $table->integer('tag_id');
    $table->timestamps();
  });
}

// Post.php
// define relationship in Post model
public function tags()
{
  return $this->belongsToMany(Tag::class);
}
content_copyCOPY

Creating tags for posts table in CMS project

https://laravel.com/docs/8.x/eloquent-relationships#many-to-many