Home > Software design >  I can't add foreign key constraint in Laravel
I can't add foreign key constraint in Laravel

Time:01-11

I'm working on small chat application using Laravel, I'm getting a migration error:

this is my migration :

Schema::create('chats', function (Blueprint $table) {
            $table->id();

            $table->integer('from_id');
            $table->integer('to_id');
            $table->text('message');

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

            $table->timestamps();
        });

Error :

 SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `chats` add constraint `chats_from_id_foreign` foreign key (`from_id`) references `users` (`id`))

I refreshed and I recreate my database, but still have the same error

CodePudding user response:

As mentioned in the comment, the reference key must have the same column type. But laravel has foreignId() method that same as default id type. For laravel 6 , the default id type is unsigned big integer, before laravel 6, the default id has unsigned integer type.

so you need to change

$table->integer('from_id');
$table->integer('to_id');

to

$table->foreignId('from_id');
$table->foreignId('to_id');

Another alternative way, just use foreignIdFor() method to create column and add foreign key in single line.

$table->foreignIdFor(\App\Models\User::class,'from_id')->constrained()->cascadeOnDelete();
$table->foreignIdFor(\App\Models\User::class,'to_id')->constrained()->cascadeOnDelete();

CodePudding user response:

You must follow the same datatype with unsigned for foreign key. By default laravel uses bigint so you must use unsignedBigInteger

Schema::create('chats', function (Blueprint $table) {
            $table->id();

            $table->unsignedBigInteger('from_id');
            $table->unsignedBigInteger('to_id');
            $table->text('message');

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

            $table->timestamps();
        });
  •  Tags:  
  • Related