Search code examples
laravellaravel-migrations

Using Laravel's foreignIdFor method and create a composite unique key


Following the syntax below, I can easily create a composite unique key based on the fields name and bakery_id:

Schema::create('product_categories', function (Blueprint $table) {
    $table->id();
    $table->foreignId('bakery_id')->constrained();
    $table->string('name', 30);
    $table->boolean('enabled')->default(true);
    $table->timestamps();

    $table->unique(['bakery_id', 'name']);
});

When I use the "foreignIdFor()" method instead of "foreignId()", is there a way to programmatically determine the name of the column?

Schema::create('product_categories', function (Blueprint $table) {
    $table->id();
    $table->foreignIdFor(Bakery::class)->constrained();
    $table->string('name', 30);
    $table->boolean('enabled')->default(true);
    $table->timestamps();

    $table->unique(['???', 'name']);
});

Solution

  • Just need to capture the column definition and use that:

    Schema::create('product_categories', function (Blueprint $table) {
        $table->id();
        $colDef = $table->foreignIdFor(Bakery::class)->constrained();
        $table->string('name', 30);
        $table->boolean('enabled')->default(true);
        $table->timestamps();
    
        $table->unique([$colDef->name, 'name']);
    });