logo
podcast Podcast
get help Get Unstuck

Why I always add a primary key to many-to-many tables

Even when Laravel doesn't require it

Joel Clermont
Joel Clermont
2024-03-12

By default, Laravel does not require a primary key on many-to-many tables. The relationship will work just fine without it.

But there are reasons you might still want to add one. For example, I was recently helping someone migrate from a single instance of MySQL to a managed MySQL cluster provided by Digital Ocean.

While not 100% required, they strongly recommend that every table has a primary key, in order to improve the reliability and performance of replication between database nodes.

No special configuration is needed in Laravel to enable the primary key, other than adding a column with a migration using $table->id(). You can do this when originally creating the table or you can add it later, perhaps after reading this tip.

Here to help,

Joel

P.S. Would you like some help moving your database onto more resilient infrastructure? Let's talk!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.