Should pivot tables in Laravel use UUIDs or auto-incrementing IDs?

In Laravel, pivot tables are used to define many-to-many relationships between two models. When creating a pivot table, one has the option of defining an auto-incrementing id field as the primary key or using a UUID instead.

For example, consider the following pivot table that links a benefits table with a units table:

Schema::create('benefit_unit', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->uuid('benefit_id');
    $table->uuid('unit_id');
    $table->timestamps();

    $table->foreign('benefit_id')->references('id')->on('benefits');
    $table->foreign('unit_id')->references('id')->on('units');
});

As you can see, this pivot table uses UUIDs as primary keys instead of auto-incrementing IDs.

My question is: does it make any sense to use UUIDs for pivot tables, or is it better to use auto-incrementing IDs like the default behavior in Laravel? Are there any potential security advantages to using UUIDs for pivot tables, or are there any downsides to using them?

>Solution :

I readed an amazing post about this recently. The conclusion of the article is this:

But based on our experience, 95% of the time, the default choice should ? always be Auto Increment Integer. Why?
Readability, and readability leads simplicity. Number is easy to write, easy to remember and easy to communicate. The primary key is not only used by the system, it’s also exposed to the end user (e.g. order #), inspected by the operation engineer, customer suppport etc…

If you want more details about that, this is the post: https://www.bytebase.com/blog/choose-primary-key-uuid-or-auto-increment

Leave a Reply