Already I have a table name table_one.
Now I want to add two more columns to it. Everything works fine so far. But in my method, I want to check a column exists or not in my table like dropIfExists('table').
/** * Run the migrations. * * @return void */ public function up() { Schema::table('table_one', function (Blueprint $table) { $table->string('column_one')->nullable(); $table->string('column_two')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('table_one', function (Blueprint $table) { // in here i want to check column_one and column_two exists or not $table->dropColumn('column_one'); $table->dropColumn('column_two'); }); }
Solution to this is Schema::hasTable() method. So, if table flights does not exist, then we create it. Of course, it can be used in a positive way – for example, if we want to add a new column to existing table, then we may check if table does exist.
A migration class contains two methods: up and down . The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method.
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'); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With