Search code examples
laravelmigrationunique

How to add unique constraint to an existing foreignId column in laravel?


I have an existing table in database with data and I want to add unique constraints to the customer_id column in it.

I tried doing $table->foreignId('customer_id)->unique()->change(). But it doesn't seem to work. The same works for any non foreign fields like string and int.

Error:

SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'customer_id' (SQL: alter table `partner_preferences` add `customer_id` bigint unsigned not  

null)


Solution

  • foreignId() essentially creates a new column which in your case already exists.

    The foreignId method is an alias of the unsignedBigInteger method:

    laravel - difference between foreignId() and unsignedBigInteger()

    Try this please:

    Unique constraint

        public function up()
        {
            // Change the 'table name' according to your needs.
            Schema::table("employees", function (Blueprint $table) {
    
                $table->unique('customer_id');
            });
        }
    

    WARNING: Make sure the column(s) that you're applying this constraint to is actually unique. (Must have unique data.)

    Otherwise, an error (SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'XXXX_customer_id_unique') will be thrown.