Posted in Laravel

Change order of migration in Laravel

When tables are migrated in Laravel with foreign key checks, MySQL doesn’t allow us to create a foreign key reference to the parent table from the child table without parent table being created. Sometimes, when we create migrations, we would have ended up creating a child table before a parent table is created. But still, there is a way to change the order of execution of table migrations.

Method 1: Changing the timestamps

Consider users table has a foreign key reference to profiles table. But unfortunately, you end up creating users table first and then profiles table. So your migrations folder will have following structure:

2017_01_01_00001_create_users_table.php
2017_01_01_00003_create_profiles_table.php

Just change the timestamp of both the files:

2017_01_01_00001_create_profiles_table.php
2017_01_01_00003_create_users_table.php

Now the profiles table is created first and then the users table.


Method 2: Create separate migration for foreign key

After creating two tables in any order, say:

2017_01_01_00001_create_users_table.php
2017_01_01_00003_create_profiles_table.php

Then create a new migration file

2017_01_01_00005_add_user_foreign_key.php

Fill your up and down functions:

public function up()
{
   Schema::table('users', function (Blueprint $table) {
      $table->foreign('profile_id')->references('id')->on('profiles')->onDelete('cascade');
   });
}

public function down()
{
   Schema::table('users', function(Blueprint $table)
   {
      $table->dropForeign('profile_id'); 
   });
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s