Removing column from database in Laravel 5+
I've a blog for which the articles
table Schema
is defined like this:
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->string('thumb')->nullable();
$table->text('excerpt');
$table->text('body');
$table->string('slug')->unique();
$table->integer('comment_count')->unsigned()->default(0);
$table->integer('view_count')->unsigned()->default(0);
$table->timestamps();
$table->softDeletes();
}
public function down()
{
Schema::drop('articles');
}
I want to drop the columns comment_count
and view_count
without losing existing data in the table
I defined a new migration like this:
class RemoveCommentViewCount extends Migration
{
public function up()
{
//nothing here
}
public function down()
{
Schema::table('articles', function($table) {
$table->dropColumn('comment_count');
$table->dropColumn('view_count');
});
}
}
and I did php artisan migrate
. It did migrate successfully, but the two columns are not dropped.
What am I doing wrong? How can I drop those columns without losing the existing data in the table?
Your migration must look like this:
Class RemoveCommentViewCount extends Migration
{
public function up()
{
Schema::table('articles', function($table) {
$table->dropColumn('comment_count');
$table->dropColumn('view_count');
});
}
public function down()
{
Schema::table('articles', function($table) {
$table->integer('comment_count');
$table->integer('view_count');
});
}
}
The dropColumn in the up method, because with new migration you want to delete this columns. If you make a rollback, you have another time the two columns
Even you can drop the multiple columns in a single line by passing the array column to dropColumn
function.
class RemoveCommentViewCount extends Migration
{
public function up()
{
Schema::table('articles', function($table) {
$table->dropColumn(['comment_count', 'view_count']);
});
}
public function down()
{
Schema::table('articles', function($table) {
$table->integer('comment_count');
$table->integer('view_count');
});
}
}
In case you have a foreign key constraint, then drop first the foreign key index association and then can pass the column to dropColumn
function with others like following.
public function up()
{
Schema::table('customer_orders', function($table) {
$table->dropForeign(['product_id']);
$table->dropForeign(['shipping_address_id']);
$table->dropColumn(['product_id', 'shipping_address_id', 'column1', 'column2']);
});
}