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

mallorca's avatar

Change foreign key to cascade instead of set null

hi artisans

Earlier, I made a foreign key that gets set to null after delete, like this:

$table->foreign('club_id')->references('id')->on('clubs')->onDelete('set null');

I would like to change that to cascade now instead. So I added the doctrine/dbal library as a dependency and did a new migration like this:

        Schema::table('users', function($table){
        $table->foreign('club_id')->references('id')->on('clubs')->onDelete('cascade')->change();
     });

But when I run the migration, I get

 SQLSTATE[23000]: Integrity constraint violation: 1022 Can't write; duplicate key in table

What am I doing wrong?

0 likes
4 replies
tykus's avatar

Have you dropped your original foreign key first?

1 like
mallorca's avatar

@tykus_ikus Thanks for your reply!

I haven't, Is it not possible to just change it?

On another note: I already have data in that db, I suppose deleting it would delete all the data associated to the table? How should I handle that?

tykus's avatar
tykus
Best Answer
Level 104

@Augustus I don't believe Laravel does anything to above and beyond what you;d have to do at the database directly; you need to remove the old FK constraint before creating a new one. Your constraint is separate to the actual field, so you can remove the constraint without deleting the actual column

$table->dropForeign('users_club_id_foreign');

Note backup your table before making changes!!

1 like
mallorca's avatar

@tykus_ikus Great, dropping the foreign key before seemed to make it work, thanks! What is the reason that it needs to be dropped and can't be changed directly?

Please or to participate in this conversation.