Laravel Advance | How to Add Foreign Key in Laravel Migration

php artisan make:migration create_posts_table
<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;class CreatePostsTable extends Migration{/*** Run the migrations.** @return void*/public function up(){Schema::create('posts', function (Blueprint $table) {$table->id();$table->string('name');$table->text('body');$table->timestamps();});Schema::create('comments', function (Blueprint $table) {$table->id();$table->unsignedBigInteger('user_id');$table->unsignedBigInteger('post_id');$table->text('comment');$table->timestamps();$table->foreign('user_id')->references('id')->on('users');$table->foreign('post_id')->references('id')->on('posts');});}/*** Reverse the migrations.** @return void*/public function down(){Schema::dropIfExists('comments');Schema::dropIfExists('posts');}}
php artisan migrate
Laravel Advance | How to Add Foreign Key in Laravel Migration
Schema::create('comments', function (Blueprint $table) {$table->id();$table->foreignId('user_id')->constrained();$table->foreignId('post_id')->constrained();$table->text('comment');$table->timestamps();});

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store