PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 13, 2022

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

 April 13, 2022     laravel, migration, unique     No comments   

Issue

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.



Answered By - steven7mwesigwa
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing