Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set existing foreign key column to nullable in alter table migration

Tags:

php

laravel

I first created a migration like this:

Schema::create('table1',function(Blueprint $table){
        $table->bigIncrements('id');
        $table->string('name')->unique();
        $table->integer("user_id")->unsigned();
        $table->foreign("user_id)->references("id")->on("users");
});

Then i wanted to add nullable property to user_id column , i wrote this migration:

Schema::table('f_subjects', function (Blueprint $table) {
        $table->integer('user_id')->nullable()->change();
        $table->foreign('original_law_id')->references('id')->on('f_original_law');
    });

But i got this error:

Cannot change column 'user_id': used in a foreign key constraint 'table1_user_id_foreign'
like image 884
sa-fm Avatar asked Jan 10 '18 13:01

sa-fm


2 Answers

1- Delete your foreign key

$table->dropForeign('table1_user_id_foreign');

2- Change user_id column definition:

//If user_id is not unsigned remove unsigned function
$table->integer('user_id')->nullable()->unsigned()->change();   

3- Create index

$table->foreign('user_id')->references('id')->on('users');

Complete migration:

Schema::table('table1',function(Blueprint $table){
    //Or disable foreign check with: 
    //Schema::disableForeignKeyConstraints();
    $table->dropForeign('table1_user_id_foreign');
    $table->integer('user_id')->nullable()->unsigned()->change();
    //Remove the following line if disable foreign key
    $table->foreign('user_id')->references('id')->on('users');
});
like image 177
ramin ashrafimanesh Avatar answered Nov 15 '22 04:11

ramin ashrafimanesh


1. You need to drop the constraint first:

$table->dropForeign(['user_id']);

2. Or you could temporarily disable FK constraints:

Schema::disableForeignKeyConstraints();

And then enable constraints:

Schema::enableForeignKeyConstraints();

https://laravel.com/docs/5.5/migrations#foreign-key-constraints

like image 45
Alexey Mezenin Avatar answered Nov 15 '22 04:11

Alexey Mezenin