Laravel Remove Column in Migration Table Code Example

Jan 13, 2023 . Admin



Hi dev,

In this quick example, let's examine how to remove a column using Laravel migration. This post includes a simple example of how to remove a column from a Laravel migration. I'd want to show how to remove a column using Laravel migration.

I'll use a few examples to show you how to quickly remove columns using migration. Here is an example that will assist you.

Example 1: Remove Column using Migration
Database\Migrations\ChangePostsTableColumn.php
<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class ChangePostsTableColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('body');
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          
    }
}
Example 2: Remove Multiple Column using Migration Database\Migrations\ChangePostsTableColumn.
<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class ChangePostsTableColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn(['body', 'title']);
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          
    }
}    
Example 3: Remove Column If Exists using Migration Database\Migrations\ChangePostsTableColumn.
<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class ChangePostsTableColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (Schema::hasColumn('posts', 'body')){
  
            Schema::table('posts', function (Blueprint $table) {
                $table->dropColumn('body');
            });
        }
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          
    }
}    

I hope it can help you...

#Laravel