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>