How to Drop Column from Table Migration in Laravel?

13-Jan-2023

.

Admin

How to Drop Column from Table Migration in Laravel?

Hi dev,

Now let us explore how to remove a column using laravel migration in this brief example. you will find a straightforward example of how to drop a column in a laravel migration in this post. i'd like to demonstrate laravel migration to remove a column. drop field laravel migration is what we'll use.

I'll use a few examples to show you how to quickly remove columns using migration. Here is an example that will assist you.

Example 1: Remove Column using Migration


Database\Migrations\ChangePostsTableColumn.php

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

{

}

}

Example 2: Remove Multiple Column using Migration

Database\Migrations\ChangePostsTableColumn.

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

{

}

}

Example 3: Remove Column If Exists using Migration

Database\Migrations\ChangePostsTableColumn.

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

{

}

}

I hope it can help you...

#Laravel