Laravel Migrations: how to drop a foreign key column - developed.be

Sometimes it can be desirable to remove a database column that hosts a foreign key relationship (eg: in reverse migration scripts). It can be a bit of a hassle to get that done.

Here’s how to do it:

1) Log in to your database and lookup the name of the foreign key relationship. If you use phpmyadmin, go to the table, click the “Structure” tab, click the link “Relation View” and wait a few seconds for it to load. Search for the field “Constraint name”. In my example this is: “contribution_copyright_id_foreign”

2) Go to the Laravel migration script (or create one). The trick is to first drop the foreign key relationship and then drop the column.

 public function down()
 {
        Schema::table('contribution', function(Blueprint $table){
            $table->dropForeign('contribution_copyright_id_foreign');
            $table->dropColumn('copyright_id');
        });

If you want to remove a table where a foreign key is present, you also first have to drop the foreign key relationship.


Rss Comments

Comments

No comments yet.

Leave a comment