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

grantjames's avatar

Foreign key constraint naming

Hi all,

I'm implementing polymorphic many to many relationships. My table structure is identical to that shown in the Laravel documentation: https://laravel.com/docs/4.2/eloquent#many-to-many-polymorphic-relations

I remember experimenting with a standard many to many relationship in the past and noticed that without setting a foreign constraint on the pivot table, there would be "orphaned" records left around after deleting from one of the tables. For example, if I had a Posts table and a Tags table and deleted a Post, I'd no longer want the joining record in the pivot table and since Laravel doesn't delete it automatically I'd need to set a foreign key constraint with ON DELETE CASCADE to delete it.

Now I want to apply the Tags to multiple models, I'm trying the same technique adding the foreign key, but of course Laravel's schema builder automatically names the foreign key constraints for you, so the following doesn't work...

$table->foreign('taggable_id')->references('id')->on('videos')->onDelete('cascade');
$table->foreign('taggable_id')->references('id')->on('posts')->onDelete('cascade');

When running the migration, it complains that the constraint "taggables_taggable_id_foreign" already exists.

So I suppose my question is - should I manually write out the SQL for the constraint to my database migration or am I approaching the whole thing incorrectly?

Thanks in advance.

0 likes
5 replies
tykus's avatar

You misunderstand what a foreign key constraint does - Laravel will have no responsibility for deleting the related records, this happens in the database.

Now, as to naming, just pass a second string to the foreign() method to name the constraint yourself.

5 likes
grantjames's avatar

Many thanks! The second param to the foreign() method is what I was searching for.

etccnfg's avatar

What is the reason of giving custom names?

meyegui's avatar

@etccnfg Giving custom names can be useful if you have your own naming convention.

I also find it helpful to be explicit in naming things, so I can look at my migrations to know the name of an index if I ever want to drop it later.

Please or to participate in this conversation.