How to remove a column from existing tables using Laravel migrations?

In this post, you’ll learn how to remove a column from an existing table in Laravel using migrations.
Suppose you want to remove the slug field from the products table.

1. Create the migration

Create the migration where –table=your-table-name flag specifies the table from which You want to remove the column.

php artisan make:migration remove_slug_from_products_table --table=products

This command will create a new migration class in the migrations folder, where you have to add the column (slug) you want to remove.

2. Add the follow code in the up() method

public function up()
{
Schema::table('products', function (Blueprint$table) {
    $table->dropColumn('slug');
});
}

3. Reverse the migration in the down() method

publicfunctiondown()
{
Schema::table('products', function (Blueprint$table) {
    $table->json('slug')->after('name');
});
}

4. Run the Migration

Finally, run the migration command and the slug column will be removed from the table.

php artisan migrate

Read more here about Dropping Columns in Laravel

Leave a Comment

How to? Ask a Question