How to add a foreign key to an existing table

Hi I’m using laravel 10 and wanted to add a foreign key to an already existing table

    public function up(): void
    {
        Schema::disableForeignKeyConstraints();

        Schema::table('channels', function (Blueprint $table) {
            $table->foreignIdFor(App\Models\User::class)
            ->after('name')
            ->constrained();
        });

        Schema::enableForeignKeyConstraints();
    }

    public function down(): void
    {
        Schema::table('channels', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
            $table->dropColumn('user_id');
        });
    }

I disabled the foreign key verification with command Schema::disableForeignKeyConstraints(), but I still get an error.

SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL (Connection: sqlite, SQL: alter table “channels” add
column “user_id” integer not null)

Please tell me how to fix it

Leave a Comment