Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

majster-pl's avatar

Database relations and conditional unique key

Hi All, this is my first post here so please excuse me if format is incorrect.

I'm developing small API back end for my webapp and looking for solution to following problem: I have 3 tables: Users:

        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->unsignedBigInteger('owner_id')->nullable();
            $table->timestamps();
            $table->foreign('owner_id')->references('id')->on('companies');
        });

Customers:

        Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('customer_name')->unique();
            $table->timestamps();
            $table->unsignedBigInteger('owner_id');
            $table->foreign('owner_id')->references('id')->on('companies');
        });

Companies:

        Schema::create('companies', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->timestamps();
        });

I want to be able to customer table to have unique name column but for individual foreign key on owner_id. For example: There can be two customers with the same name but different foreign key.

Thank you for any suggestions, if this is not possible I would appreciate to point me to right direction to accomplish this, thank you!

0 likes
5 replies
anilkumarthakur60's avatar
  Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->timestamps();
            $table->foreignId('company_id')->nullable()->constrained('companies');
        });
    Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('customer_name')->unique();
            $table->timestamps();
		      $table->foreignId('company_id')->unique()->constrained('companies');


        });
  Schema::create('companies', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->timestamps();
        });

make sure companies table migrate first

anilkumarthakur60's avatar

@waliczek.szymon@gmail.com in my comment customer migration have a look again $table->foreignId('company_id')->unique()->constrained('companies'); it should work

orest's avatar
orest
Best Answer
Level 13
$table->unique(['customer_name', 'owner_id']);

Please or to participate in this conversation.