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']);
});

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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']);
});

Method 2

I don’t get your question but maybe this might help

Schema::create('product_categories', function (Blueprint $table) {
   $table->id();
   // $table->foreignIdFor(Bakery::class)->constrained();
   $table->unsignedInteger('bakery_id')->nullable();
   $table->foreign('bakery_id')->references('id')->on('bake')->onDelete('cascade');
   $table->string('name', 30);
   $table->boolean('enabled')->default(true);
   $table->timestamps();

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x