Monday, March 6, 2017

Cannot drop multiple foreign keys using single migration file in laravel 5?

I am trying to drop multiple user_id foreign_keys from multiple tables but I am in a weird bug where only the first table is working fine and the constraint doesn't get removed from others.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class DropUserIdForeignKeyConstraintFromTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('accessible_by_user', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });

        Schema::table('document_term', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });

        Schema::table('file', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });

        Schema::table('order', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });

        Schema::table('role_user', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });

        Schema::table('termable', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('accessible_by_user', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
        });

        Schema::table('document_term', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
        });

        Schema::table('file', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
        });

        Schema::table('order', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
        });

        Schema::table('role_user', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
        });

        Schema::table('termable', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
        });
    }
}

So the foreign key drops from accessible_by_user just fine but not from any other table. Although when I tried a dd('hello') in second schema, it did dump so that code is running I can tell.

Do I need multiple migration files to remove foreign keys from multiple tables?



via Rohan

Advertisement