'Maintaining SQLite databases in Laraval - Adding foreign-key constraint to existing table omitted

While running Laravel (v8.75) with SQLite I encounter problems creating a new foreign-key relation to the existing users table.

Migrations:

// New model UserType
Schema::create('user_types', function (Blueprint $table) {
    $table->integer('id');
    $table->string('name');
});

// Existing model User
Schema::table('users', function (Blueprint $table) {
    $table->integer('user_type_id')->after('id');
    $table->foreign('user_type_id')->references('id')->on('user_types');   <----- is not being created!
});

The migration runs successfully, but the foreign-key constraint is missing.

During my web researches I found a related issue report on Github: https://github.com/laravel/framework/issues/24876

I can read there, that SQLite officially not supports altering table constraints: https://www.sqlite.org/omitted.html

> Other kinds of ALTER TABLE operations such as ALTER COLUMN, ADD CONSTRAINT, and so forth are omitted.

When the foreign-key constraint is created in the create-process of the table, then the foreign-key gets created fine!

The strange thing about this issue is, that with "DB Browser for SQLite" it is (!) possible to add a new foreign-key constraint also to the existing users table successfully!

Therefore I don't get, why it is not working in any way with Laravel...

Addittion, config database shows enabled foreign-key support:

'sqlite' => [
    'driver' => 'sqlite',
    'url' => env('DATABASE_URL'),
    'database' => env('DB_DATABASE', database_path('database.sqlite')),
    'prefix' => '',
    'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],

Do you guys have an idea, how to get such afterwards migrations to work automatically via a Laravel migration? Or is it really the last option to migrate productive data in a newly created db structure?

Any practical experience and tips on this topic would be helpful... Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source