Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tjventurini/707ee330f6bfb7db08c3d34d73db5b1d to your computer and use it in GitHub Desktop.
Save tjventurini/707ee330f6bfb7db08c3d34d73db5b1d to your computer and use it in GitHub Desktop.
Laravel Migration for Pivot Table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostTagPivotTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::transaction(function () {
Schema::create('post_tag', function (Blueprint $table) {
// create post_id column
// ! make sure to use the same column type
// as in the referenced column
// e.g. integer or bigInteger
$table->bigInteger('post_id')
->unsigned()
->nullable();
// make post_id column a foreign key
$table->foreign('post_id')
->references('id')
->on('posts')
->onDelete('cascade');
// create tag_id column
// ! make sure to use the same column type
// as in the referenced column
// e.g. integer or bigInteger
$table->bigInteger('tag_id')
->unsigned()
->nullable();
// make tag_id column a foreign key
$table->foreign('tag_id')
->references('id')
->on('tags')
->onDelete('cascade');
});
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('post_tag');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment