laravel migration add foreign key to existing table

You can add a foreign key to the existing table in laravel using migration. Laravel provides migration column type foreginId() which helps you to create a foreign key in an already existing table in your database.

Answers 1
  • Create foreign key to an existing table in laravel 8

    //Create migration file
    php artisan make:migration add_user_id_to_posts_table --table=posts
    
    //Create table structure using column type in the generated migration file
    //database\migrations\<2021_07_26_032616>_add_user_id_to_posts_table.php
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->foreignId('user_id')->constrained();
        });
    }
    
    /**
        * Reverse the migrations.
        *
        * @return void
        */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });
    }
    
    //Run artisan command to create a foreign key
    php artisan migrate
    
    0

    Laravel 8 has a foreignId() column type in migration schema builder. Which is used to create a foreign key in laravel with an UNSIGNED BIGINT equivalent column.

  • Back to code snippet queries related laravel

Related queries helps you to understand and may also used for implementation of current code snippet