Laravel migration to add nullable attribute to existing table column
P粉674757114
P粉674757114 2023-09-05 12:58:02
0
1
405

I have started writing a small personal project on Laravel 10. The problem I encountered is as follows:

  1. I have a user table with a foreign key UUID - role_id.
  2. I want to add nullable attribute on this column without deleting the table.
  3. I created a new migration to make the changes.
  4. The doctrine/dbal package is installed in order to (theoretically) change columns.
  5. My code in the migration is as follows:
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(); }); }

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).

Any suggestions on how to modify the columns correctly would be greatly appreciated.

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
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!