Check If a Column Exists in Laravel Migration File

You need something just like this

  public function down()
    {
        if (Schema::hasColumn('users', 'phone'))
        {
            Schema::table('users', function (Blueprint $table)
            {
                $table->dropColumn('phone');
            });
        }
    }

You could make your own 'dropColumnIfExists()' function that checks the column existence then drop it:

function myDropColumnIfExists($myTable, $column)
{
    if (Schema::hasColumn($myTable, $column)) //check the column
    {
        Schema::table($myTable, function (Blueprint $table)
        {
            $table->dropColumn($column); //drop it
        });
    }

}

And use it on 'down()' function like this:

public function down()
{
    myDropColumnIfExists('table_one', 'column_two');
    myDropColumnIfExists('table_one', 'column_one');
}

For dynamically checking your table column you can try something like this:

public function dropIfExists($table, $column)
{
    if (Schema::hasColumn($table, $column)) //check the column
    {
        Schema::table($table, function (Blueprint $table) use ($column)
        {
            $table->dropColumn($column); //drop it
        });
    }

}

Tags:

Sql

Php

Laravel