Laravel Migration Composite key Unique on two Columns with Values

Laravel Migration Composite key Unique on two Columns with Values is today’s topic. More then time when we want to validate composite unique keys so we need to add unique two columns with Values. Basically we use Foreign Key Constraint in Laravel Migration, but here we add table two column unique with composite key. Composite key is best for not accepting duplicate entries in our table.

If you have users table other is projects table and third is user_projects table where you have user_id and project_id and you want user_id base to unique project_id then we add composite key to making these columns to unique. let’s checkout the laravel migration composite unique key on two columns with values.

Using composite key unique through you do not save same project_id twice on the the same user_id, so for this use case it’s better to use

    public function up()
    {
        Schema::table('user_projects', function (Blueprint $table) {
            $table->unique(["user_id", "project_id"], 'user_project_unique');
        });
    }

    public function down()
    {
        Schema::table('user_projects', function (Blueprint $table) {
          $table->dropUnique('user_project_unique');
        });
    }

I hope this work for you.

1 thought on “Laravel Migration Composite key Unique on two Columns with Values”

Leave a Comment