How to remove a column from a table in Laravel migration?

Spread the love

Hello Guys,

Explore the process of remove a column through Laravel migration with this concise guide. This article offers a straightforward demonstration of dropping a column within a Laravel migration. Discover the effective use of Laravel migrations for column removal tasks.

Learn how to remove a column from your database table in Laravel 6, 7, 8, 9, and 10, and grasp the ease with which it can be accomplished.

We’ll provide multiple illustrative examples to demonstrate the rapid removal of columns through migrations, ensuring you have a clear understanding of the process. Take a look at this helpful example for guidance.

Example of remove a column through Laravel migration:

Also Read: How to Remove Public From URL in Laravel 10

1) Using migration, remove the column
2) Using migration, remove many columns
3) Remove the Column Using Migration If It Exists

1) Using migration, remove the column

<?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()
    {
          
    }
}

2) Using migration, remove many columns

Also Read: How to Integrate Stripe Payment Gateway In Laravel 10

<?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()
    {
          
    }
}

3) Remove the Column Using Migration If It Exists

<?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()
    {
          
    }
}

We trust you’ll discover our Laravel Blogs to be a valuable resource.

Leave a Comment