Laravel Migration: Cannot add a foreign key of char data type

When you trying to create a foreign key of char data type. Then you run the migrate command. You may get the following error.

SQLSTATE[HY000]: General error: 1005 Can't create table `project_name`.`transaction_transfers` (errno: 150 "Foreign key constraint is incorrectly
formed") (SQL: alter table `transaction_transfers` add constraint `transaction_transfers_id_transaction_foreign` foreign key (`id_transaction`)
references `transactions` (`transaction_id`) on delete cascade)

This is your two migrations files, transactions and transaction_tasnfer tables

transactions migration file

Schema::create('transactions', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->char('transaction_id', 8);
            $table->string('type');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

transaction_transfer migration file

Schema::create('transaction_transfers', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->integer('fee')->nullable();
            $table->string('status')->nullable();
            $table->char('id_transaction', 8)->unique();
            $table->unsignedBigInteger('user_id');
            $table->foreign('id_transaction')->references('transaction_id')->on('transactions')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

If you write your migrations like above, you will get an error like this.

SQLSTATE[HY000]: General error: 1005 Can't create table `project_name`.`transaction_transfers` (errno: 150 "Foreign key constraint is incorrectly
formed") (SQL: alter table `transaction_transfers` add constraint `transaction_transfers_id_transaction_foreign` foreign key (`id_transaction`)
references `transactions` (`transaction_id`) on delete cascade)

The solution is add the transaction_id in transactions migration unique like following code

Schema::create('transactions', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->char('transaction_id', 8)->unique();
            $table->string('type');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

It’s done.

Leave a Comment