How to Add Foreign Key in Laravel Migration?

0
12

This tutorial shows how to add a foreign key constraint to a field in Laravel in the migration file. As we already know a foreign key is a field that is used to establish the relationship between two tables via the primary key. This example starts with creating a migration file in Laravel and shows how to populate this migration file with migration statements.

You can safely use this method in Laravel 6, Laravel 7, Laravel 8, Laravel 9, etc.

In this short example, we will create a table for ‘products’ and ‘images’. The images table will have a foreign key linked to the products table.

Create migration fields

Run the commands below to create migration files

php artisan make:migration create_products_table
php artisan make:migration create_product_images_table

database/migrations/2022_08_23_114617_create_products_table.php

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateProductsTable extends Migration

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    
        Schema::create('products', function (Blueprint $table) 
            $table->id();
            $table->string('name');
            $table->text('description');
            $table->decimal('price');
            $table->timestamps();
        );
    

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    
        Schema::dropIfExists('products');
    

database/migrations/2022_08_23_114656_create_product_images_table.php

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateProductImagesTable extends Migration

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    
        Schema::create('product_images', function (Blueprint $table) 
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->foreign('product_id')->references('id')->on('products');
            $table->string('image',255);
            $table->timestamps();
        );
    

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    
        Schema::dropIfExists('product_images');
    

Run migration to generate the tables in Laravel.

php artisan migrate

After tables are generated you can go to the admin database and see the product_images table’s structure. In the indexes section, you can see that there is a foreign key generated for you. For our case, it will be product_images_product_id_foreign .


Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here