Laravel migration to add nullable attribute to existing table column
P粉674757114
P粉674757114 2023-09-05 12:58:02
0
1
516
<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粉674757114
P粉674757114

reply all(1)
P粉068486220

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)');

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template