Search code examples
phpmysqllaravellaravel-5.6

Laravel drop foreign Key in Migration


I want to create a Migration which shall drop a table. I created the Migration like this:

Schema::table('devices', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('client_id')->nullable();
    $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
});

And now I try to drop it like this:

    Schema::table('devices', function (Blueprint $table) {
        $table->dropForeign('devices_client_id_foreign');
        $table->drop('devices');
    });

But I get following error:

In Connection.php line 664:

  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'devices_client_id_foreign'; check that column/key exists (SQL:

alter table devices drop foreign key devices_client_id_foreign)

In PDOStatement.php line 144:

  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'devices_client_id_foreign'; check that column/key exists


In PDOStatement.php line 142:

  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'devices_client_id_foreign'; check that column/key exists

Solution

  • You just need to disable foreign key checks before you drop the table then enable them again after like this:

    DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    Schema::dropIfExists('devices');
    DB::statement('SET FOREIGN_KEY_CHECKS=1;');