Removing column from database in Laravel 5+
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']);
});
}
Create remove column migration
php artisan make:migration RemoveCommentViewCount
The down
method is for rollbacks, so add dropColumn in your up()
function and reverse in down()
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class RemoveCommentViewCount extends Migration
{
public function up()
{
if (Schema::hasColumn('comment_count', 'view_count')){
Schema::table('articles', function (Blueprint $table) {
$table->dropColumn('comment_count');
$table->dropColumn('view_count');
//OR
$table->dropColumn(['comment_count', 'view_count']);
});
}
}
public function down()
{
Schema::table('articles', function($table) {
$table->integer('comment_count');
$table->integer('view_count');
});
}
}
Check laravel documentation on dropping columns migrations
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