Implementing UUID as primary key in Laravel intermediate table

49 views Asked by At

I'm interested in using UUIDs as primary keys in an intermediate table. I'm aware that adding use Illuminate\Database\Eloquent\Concerns\HasUuids; and use HasUuids; to a model can achieve this. However, since I don't have or need a model for my intermediate table, I'm uncertain if it's possible to automatically create UUIDs similarly. Will I need to manually generate the UUID when I create an entry in my intermediate table?

Here's what my migration file looks like:

public function up(): void {
    Schema::create('post_user', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->timestamps();
        $table->string('title');
        $table->string('body');
    });
}
1

There are 1 answers

1
Karl Hill On

In Laravel, UUIDs can be automatically generated for models using the HasUuids trait. However, for intermediate tables without a model, you would need to manually generate the UUID when creating an entry. One way to do this is using Laravel's built-in Str::uuid() method when inserting data into the table.

DB::table('post_user')->insert([
    'id' => (string) Str::uuid(),
    'title' => $title,
    'body' => $body,
    'created_at' => now(),
    'updated_at' => now(),
]);