Recently i wanted to change a nullable column into “not nullable” column. For this i created a new laravel migration:
php artisan make:migration update_product_price_table
The column “price” was a nullable column. I want change the column with “default(0)”. For this matter i added following code:
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('products', function (Blueprint $table) {
$table->integer('price')->default(0)->change();
});
}
};
To update the table i executed following command:
php artisan migrate
This command delivered following error:
SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'price' (Connection: mariadb, SQL: alter table `products` add `price` int not null default '0')
The error refers to that in the product table there are rows with price column having null value. That’s why we have to update all price values in the product table, so there is no rows left with null value:
UPDATE `products` SET `price` = '0' WHERE `price` IS NULL
Now when i execute the laravel migration command “artisan migrate”, the table will be updated without a problem.