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

davidyu's avatar

How to change the unique constraint in a migration

Say I already have a unique constraint from a existing migration $table->unique(['candidate_id', 'voter_id', 'type']); How can I change this unique constraint?

0 likes
3 replies
davidyu's avatar
davidyu
OP
Best Answer
Level 2

Yes this is what I am doing now to change the unique constraint is there a better way? this is what I have for the migration

 public function up()
    {
        Schema::table('votings', function (Blueprint $table) {
            $table->string('position')->nullable();

            $table->dropUnique(['candidate_id', 'voter_id', 'type']);
            $table->unique(['candidate_id', 'voter_id', 'type', 'position']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('votings', function (Blueprint $table) {
            $table->dropColumn('position');

            $table->dropUnique(['candidate_id', 'voter_id', 'type', 'position']);
            $table->unique(['candidate_id', 'voter_id', 'type']);
        });
    }

Basically all I really want to do is add position into the unique constraint but it doesn't feel very clean in its current state.

4 likes

Please or to participate in this conversation.