Home  >  Q&A  >  body text

Laravel migration to add nullable attribute to existing table column

<p>I have started writing a small personal project on Laravel 10. The problem I encountered is as follows: </p> <ol> <li>I have a user table with a foreign key UUID - role_id. </li> <li>I want to add nullable attribute on this column without deleting the table. </li> <li>I created a new migration to make the changes. </li> <li>The doctrine/dbal package is installed in order to (theoretically) change columns. </li> <li>My code in the migration is as follows: </li> </ol> <pre class="brush:php;toolbar:false;">public function up(): void { Schema::table('users', function (Blueprint $table) { $table->foreignUuid('role_id')->nullable()->constrained('roles')->change(); }); } /*** Reverse the migrations.*/ public function down(): void { Schema::table('users', function (Blueprint $table) { $table->foreignUuid('role_id')->nullable(false)->constrained('roles')->change(); }); }</pre> <p>But when I run php artisan migrate, I get the following error - SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'role_id' (Connection: mysql, SQL: alter table users add role_id char(36 ) null). </p> <p>Any suggestions on how to modify the columns correctly would be greatly appreciated. </p>
P粉674757114P粉674757114411 days ago459

reply all(1)I'll reply

  • P粉068486220

    P粉0684862202023-09-06 00:54:03

    You can try the following:

          Schema::table('users', function (Blueprint $table) {
                $table->char('role_id', 36)->nullable()->constrained('roles')->change();
            });
    

    Or you can use the original SQL statement:

        DB::statement('ALTER TABLE users MODIFY role_id CHAR(36) NULL');
        DB::statement('ALTER TABLE users ADD CONSTRAINT fk_users_role_id FOREIGN KEY (role_id) REFERENCES roles (id)');
    
    

    reply
    0
  • Cancelreply