Drop foreign key column in Laravel using migration

Created at 15-Nov-2021 , By samar

Drop foreign key column in Laravel using migration

We’ll attempt to use programming in this lesson to solve the "Drop foreign key column in Laravel using migration" puzzle.

You can drop foreign key column with constraints in Laravel using migration, you have to create migration file and add dropForeign() and dropColumn() method inside up or down function in migration file and run migration command to drop the column.
  • Drop foreign key constraint posts_user_id_foreign from posts table with column in Laravel using migration

    --PATH database\migrations\<2021_11_15_101237_drop_posts_user_id_foreign_from_posts>.php
    public function up(){
        Schema::table('posts', function(Blueprint $table){
            $table->dropForeign('posts_user_id_foreign');
            $table->dropColumn('user_id');
        });
    }
    

    To get the foreign key constraint, click on table in the specific database and click on relation view after click on structure of the table.

    Create migration file using php artisan make:migration drop_posts_user_id_foreign_from_posts --table=posts command.

    Add the foreign key constraint to the dropForeign method which you want to drop and run migration command to drop the column and foreign key constraint.

  • Drop foreign key constraint with index and column in Laravel using migration

    --PATH database\migrations\<2021_11_15_101237_drop_posts_user_id_foreign_from_posts>.php
    public function up(){
        Schema::table('posts', function(Blueprint $table){
            $table->dropForeign('posts_user_id_foreign');
            $table->dropIndex('posts_user_id_foreign');
            $table->dropColumn('user_id');
        });
    }
    

    Using this code snippet you can drop foreign key column with index and constraint name in Laravel.

    To get the foreign key constraint, click on table in the specific database and click on relation view after click on structure of the table.

    Create migration file using php artisan make:migration drop_posts_user_id_foreign_from_posts --table=posts command.

    Add the foreign key constraint to the dropForeign method which you want to drop and run migration command to drop the column and foreign key constraint.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.