Dave Hulst
Dave Hulst

Reputation: 39

How can I create unique index, that requires a set of attributes to be unique?

Hello Stack overflowers

I came up with a problem with Laravel, and I'm not sure how I can solve it.

The situation is as following:

I got a migration, with the name 'adresses':

Schema::create('adresses', function (Blueprint $table) {
    $table->id();
    $table->string('adress'); //adress
    $table->integer('houseNumber'); //house number
    $table->string('houseNumberAddition')->nullable(); //house number addition
    $table->timestamps();
});

What I would like to achieve: I want the adress, houseNumber and houseNumberAddition together, to become 1 unique value.

Normally you would add the unique() function, to make specific fields unique. But I want the combination of adress, houseNumber and houseNumberAddition together, to become one unique value.

(because houseNumber and houseNumberAddition will be used more than once, while the combination with adress, houseNumber and houseNumberAddition will only exist once in my database.)

I hope somebody got some fancy trick to solve this.

Thanks for helping!

Dave

Upvotes: 0

Views: 496

Answers (1)

SillasSoares
SillasSoares

Reputation: 382

You may combine the 3 columns in one unique index

$table->unique(['adress', 'houseNumber', 'houseNumberAddition']);

Upvotes: 2

Related Questions