Remove/drop column from existing table using migration in laravel; Through this tutorial, we will learn how to remove/drop columns from existing table using migration in laravel 10|9|8 apps.
Laravel 10|9|8 Migration Drop Columns From Existing DB Table
There are a three condition and solution has been available to remove or drop columns from exiting table using migration in laravel 10|9|8; as follows:
- Drop Column using Migration
- Drop Multiple Column using Migration
- Drop Column If Exists using Migration
Let us assume that we have a post table in our database. And we have to delete some columns from that table. So for this, we have to first create a migration file.
Before using the solution given below, we should create a migration file by using the command given below:
php artisan make:migration drop_posts_table_columns --table=posts
Note:- The above command was made for understanding only. We can name our migration file whatever.
Drop Column using Migration
In DropPostsTableColumn class content a up() method, which is used to remove column from table using migration in laravel:
<?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() { }
Drop Multiple Column using Migration
In DropPostsTableColumn class content a up() method, which is used to remove or drop multiple column from table using migration in laravel:
<?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() { } }
Drop Column If Exists using Migration
Use the following method to remove or drop column if exits using migration in laravel:
<?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.