How to add foreign key in table using migration in Laravel
In this article we will see how to add foreign key on your table while creating using migration in Laravel .
Table - 1 : student
public function up() { Schema::create('student', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('address'); $table->string('phone'); $table->string('about')->nullable(); $table->timestamps(); }); }
Table - 2 : section
public function up() { Schema::create('section', function (Blueprint $table) { $table->id(); $table->bigInteger('student_id')->unsigned()->index()->nullable(); $table->foreign('student_id')->references('id')->on('student')->onDelete('cascade'); $table->string('section')->nullable(); $table->string('stream')->nulable(); $table->timestamps(); }); }
Now simply run your migration command as shown below .
php artisan migrate
Table Structure :
This is how you can add foreign key to your table . if you want yo know how to add column , drop column and change column property click on this link .
Thank you for reading this article 😊
For any query do not hesitate to comment 💬