Check If a Column Exists in Laravel Migration File Check If a Column Exists in Laravel Migration File laravel laravel

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');}


Just break the schema up into two calls

public function up(){    Schema::table('table_one', function (Blueprint $table) {        $table->dropColumn(['column_one', 'column_two']);    });    Schema::table('table_one', function (Blueprint $table) {        $table->string('column_one')->nullable();        $table->string('column_two')->nullable();    });}