Laravel Migration change existing column to nullable
I'm trying to update my update my colab column in my projects table but it seems like my eloquent query is wrong perhaps cause it is not updating the column.
public function up()
{
Schema::table('projects', function (Blueprint $table) {
$table->string('colab')->nullable()->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('projects');
}
@jaythanki Hi there. A bit old topic but came across it while searching for solution. My problem is as follows:
I have users table with foreign key - role_id.
I want to alter the role_id to be nullable without dropping the table.
I have installed doctrine/dbal package.
I have created a migration to do the alteration.
The current state of the code in the migration is:
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 follwoing error - SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'role_id' (Connection: mysql, SQL: alter table users add role_id char(36) null).
Would be very grateful for any advice how to properly do the alteration of the column.
Also make sure you have doctrine/dbal installed by running composer require doctrine/dbal first before running your migration.
For a full example (with a constrained column), see below (and note that I'm having to drop the foreign key relationship before the column can be changed; the foreign key relationship will be re-established after the column is changed):
public function up()
{
Schema::table('my_table_name', function (Blueprint $table) {
// Removes the foreign key relationship so column can be modified
$table->dropForeign('my_table_name_my_column_name_foreign');
// Changes column to nullable on migrate
$table->foreignId('my_column_name')->nullable()->change()->constrained('foreign_table_name')->onDelete('cascade')->onUpdate('cascade');
});
}
public function down()
{
Schema::table('my_table_name', function (Blueprint $table) {
// Removes the foreign key relationship so column can be modified
$table->dropForeign('my_table_name_my_column_name_foreign');
// Sets column back to NOT nullable on rollback
$table->foreignId('my_column_name')->nullable(false)->change()->constrained('foreign_table_name')->onDelete('cascade')->onUpdate('cascade');
});
}