Migrations Archives - 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.

A quick tip: if you want autocomplete (intellisense) when writing migrations in Laravel, you can add type hinting for the $table variable.

Just add Blueprint before $table in the function argument. Blueprint is the type of the $table variable. You’ll be able to see all the options and don’t have to check Laravel docs anymore.

class Payments extends Migration {
 
  public function up() {
    Schema::create('donor_account', function(Blueprint $table){
      $table->engine ='InnoDB';
      $table->increments('id');

This is how it looks in PHPStorm 8:

phpstorm_table_autocomplete