Simplify Your Workflow: Dropping Columns in Laravel with Migrations

 How to drop column from table using migration in Laravel

Simplify-Your-Workflow-Dropping-Columns-in-Laravel-with-Migrations

In this article we will learn how can you remove column from table in Laravel using migration . As we know it's a better practice to change structure of a table using migration in laravel . So let's see  how can you remove a column from table using migration .

Here in this example i have a table named ' items ' in my MySQL Database the structure is given in the below image and from this table we will remove ' catagory ' column using migration .

How to drop column in Laravel using migration

Step 1 - Create Migration :

First you have to create a migration file to write our code to drop column from table . You can use the following command to create a migration file .

php artisan make:migration drop_catagory_column_from_items_table --table=items

Now this command will create a migration file on your " database/migrations/yourfilename.php " .

Step 2 - Write migration code :


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class DropCatagoryColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('items', function (Blueprint $table) {
            if (Schema::hasColumn('items', 'catagory')){
  
                Schema::table('items', function (Blueprint $table) {
                    $table->dropColumn('catagory');
                });
            }
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('items', function (Blueprint $table) {
            //
        });
    }
}

Step 3 - Run migrate command :

Now you have to simply run your migrate command to delete the column from your table .

php artisan migrate

Step 4 - Check your table :

How to drop column in Laravel using migration


The above code will first check whether the catagory column is exist on your items table or not , if exists it will drop the catagory column otherwise it will leave the table as it is .


Previous Post Next Post

Contact Form