更新现有列属性 - Laravel 5迁移

I have

a existing column called cpe_mac. I created it via migration like this :

$table->string('cpe_mac')->default(NULL)->nullable();

I want

I want to add this ->unique() to that column, without having to drop it and re-add.


I've tried

$table->string('cpe_mac')->unique();

Migration File

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AlterCaptivePortalTable212017 extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('captive_portals', function (Blueprint $table) {
            $table->string('cpe_mac')->unique();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('captive_portals', function (Blueprint $table) {
            $table->string('cpe_mac')->default(NULL)->nullable();
        });
    }
}

I kept

getting

SQLSTATE[42701]: Duplicate column: 7 ERROR:  column "cpe_mac" of relation "captive_portals" already exists

Is there to achive this without having to drop my existing column ?

(I have a lot client data that can't be deleted !)

How would one go about and implement this ?


I'm opening to any suggestions at this moment.

Any hints / suggestions / helps on this be will be much appreciated !

You need to use change() method:

Schema::table('captive_portals', function (Blueprint $table) {
    $table->string('cpe_mac')->unique()->change();
});

Alternatively, you may create the index after defining the column. For example:

$table->unique('email');

https://laravel.com/docs/5.4/migrations#indexes

Schema::table('users', function (Blueprint $table) { $table->string('cpe_mac')->unique()->change(); });

https://laravel.com/docs/5.0/schema#changing-columns

If the column is already defined you can use:

$table->unique('cpe_mac');

I had the same issue and this is the solution for Laravel 5.6:

Step1: run this command: composer require doctrine/dbal

step2:run this command:php artisan make:migration THE -NAME_YOU_WANT --table=TABLENAME

step3: in the added migration, add $table->string('cpe_mac')->unique()->change(); in Schema::table part.

step4: run this command: php artisan migrate