Dropping a column in laravel using migrations; Simply open your migration file and add DropColumn() method along with the column name in migration file and after that, run the PHP Artisan migrate command
on CMD or command line.
The dropIfExists
is not a method on Laravel, it has dropColumn()
method to remove a column from an existing database table and hasColumn()
method to check if the column exists in the DB table with migration.
Here are three different ways to remove or drop columns from the exiting table using migration in laravel 11, 10 and 9; as follows:
Laravel Migration Drop or Remove Column from Table
Navigate to your database/migration directory and open your migration, and add dropColumn() method with column to remove or drop single column from table in laravel; is as follow:
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class DropPostsTableColumn extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->dropColumn('content'); }); } /** * Reverse the migrations. * * @return void */ public function down() { }
Laravel Migration Drop Multiple Columns
To delete multiple columns from an existing table in Laravel, you can use $table->dropColumn() method with multiple column names; You can do something like this:
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class DropPostsTableColumn extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->dropColumn(['content', 'title']); }); } /** * Reverse the migrations. * * @return void */ public function down() { } }
Laravel Migration Drop Column If Exists
There is no function named dropIfExists()
before deleting a column from the database table in Laravel, for this you have to use hasColumn()
and check the column if exists and delete it using Laravel migrations; You can use it in this way:
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class DropPostsTableColumn extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (Schema::hasColumn('posts', 'content')){ Schema::table('posts', function (Blueprint $table) { $table->dropColumn('content'); }); } } /** * Reverse the migrations. * * @return void */ public function down() { } }
Then, execute the migration command to remove column from the table.
php artisan migrate
Conclusion
Through this tutorial, we have learned how to remove/drop column from existing table using migration in laravel apps.