Today’s tutorial shows how to add a foreign key to a MySql table field in Laravel migration. I am sure you are in the right place to start with the migration and foreign key constraints in Laravel.
As we discussed earlier, the foremost purpose of the foreign key is to provide referential integrity between parent and child tables. By creating a foreign key you are enforcing a relationship between the tables. For example, you have two tables of users and addresses. So you cannot fill user_id in the address table that is not in the user table.
In this article, I will show you how to create a migration and add the foreign key constraints properly with two methods.
Method #1
Generate Migration Command
php artisan make:migration create_products_table
Open the generated file in the folder database/migrations, and the latest file in the folder which will hold the last part of the command in the filename.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); Schema::create('products_images', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('product_id'); $table->string('image'); $table->timestamps(); $table->foreign('product_id')->references('id')->on('products'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); Schema::dropIfExists('products_images'); } }
Run the below command to create the database table
php artisan migrate
If you check your database admin, you will see the new table created with the given field names.
Method #2
Modify the part where we added the migration statement for products_images table.
Like below
Schema::create('products_images', function (Blueprint $table) { $table->id(); $table->foreignId('product_id')->constrained(); $table->string('image'); $table->timestamps(); });
Run php artisan migrate and you will see the same results as Method #1
Hope you had good time with this article, please share with your friends
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.