Posts Learn Components new Snippets new Categories Tags About
/

How to Remove Column From Existing Table Migration in Laravel

Learn how to remove columns from an existing table migration in Laravel

3 months ago

5 mins read

173 views

In this short post, you'll learn to remove a column from an existing migration. The steps are very simple so let's get started. For this scenario imagine you have a "Post" model with a corresponding "create_posts_table" file and you want to remove "slug" and "summary" columns from the existing table.

Before (Post Model)

  • id
  • title
  • slug (column to be removed)
  • summary (column to be removed)
  • content
  • image

After (Post Model)

  • id
  • title
  • content
  • image
Now that we can see clearly how the table structure will look like, let's define the migration to remove the columns.

Create the Migration


To remove the columns you have to run the make migration command but instruct it as removing instead of creating a new migration. Make use of the "--table=your-table-name" flag and specify the table that you want to remove the columns.
# for multiple columns like the scenario
php artisan make:migration remove_slug_and_summary_columns_from_posts_table --table=posts

# for single column you can explicitly mention it
php artisan make:migration remove_slug_from_posts_table --table=posts
Upon success, the command will output as follows.
Created Migration: 2021_06_14_210156_remove_slug_and_summary_columns_from_posts_table

Remove the Columns


The command will create a new migration class called RemoveSlugAndSummaryColumnsFromPostsTable and here define the columns to remove from the migration in the "up" method.
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class RemoveSlugAndSummaryColumnsFromPostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn(['slug', 'summary']);
        });
    }
}
If you are dropping a column, you can just pass in the name for the "dropColumn" method.
$table->dropColumn('slug');

Run the Migration


Finally, run the migration command and the 2 columns will now be removed from the table.
php artisan migrate
By now you will be able to remove columns from an existing table. If you find this tutorial to be helpful do share it with others and cheers 🍻. happy coding!

Alternative Tags

new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻