Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

boyjarv's avatar

Setting up a foreign Key in Laravel Migration

Please help

here is my UP migration:

public function up()
    {
        Schema::create('donate_messages', function (Blueprint $table) {
            $table->id();
            $table->unsignedInteger('payment_id');
            $table->foreign('payment_id')->references('id')->on('payments')->onDelete('cascade');
            $table->string('name')->default('Anonymous');
            $table->string('message');
            $table->boolean('is_live')->default(0);
            $table->boolean('is_visible')->default(0);
            $table->timestamps();
        });
    }

and here is my error:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `donate_messages` add constraint `donate_messages_payment_id_foreign` foreign key (`payment_id`) references `payments` (`id`) on delete cascade)
0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

Typically a primary key in an unsigned big integer; so any referencing foreign key should be that same type. You are using unsigned integer, so change the column definition to match the type of the id on the payments table, e.g.

$table->unsignedBigInteger('payment_id');

Or, using the convenient foreignId method, you can make the unsigned big integer column, and define the foreign key constraint in one fluent chain:

//$table->unsignedInteger('payment_id');
//$table->foreign('payment_id')->references('id')->on('payments')->onDelete('cascade');
$table->foreignId('payment_id')->constrained('payments')->cascadeOnDelete();
anilkumarthakur60's avatar
public function up()
    {
        Schema::create('donate_messages', function (Blueprint $table) {
            $table->id();
  		   $table->string('name')->default('Anonymous');
            $table->string('message');
            $table->boolean('is_live')->default(0);
            $table->boolean('is_visible')->default(0);
			$table->foreignId('payment_id')->constrainted('payments')->cascadeOnDelete();
            $table->timestamps();
        });
    }

make sure your payments table migrate first and then donate_messages means your migration order must be like payment table migrating before donate_messages table

2021_08_20_074140_create_payments_table
2021_08_20_074140_create_donate_messages_table
1 like

Please or to participate in this conversation.