Create Many-To-Many Relationship


Fri Jul 30 2021 00:28:21 GMT+0000 (UTC)

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) {

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

Creating tags for posts table in CMS project