How to delete a column from table in Laravel

Categorized as Laravel Tagged

To remove a column from a database table in Laravel, you need to create a migration, edit, and then run it in the command line interface.

Create the migration

You need to open your Laravel application folder in Terminal. Then run one of the following commands. Remember that you can skip typing underscore symbols, see the code:

// The old way (it still works)
php artisan make:migration remove_column_from_posts_table --table=posts

// The new way
php artisan make:migration "remove column from posts table" --table=posts

You can also specify the table name, using --table=posts definition at the end of the line.

Edit the migration

Now go to your Laravel application folder /database/migration/ and open the migration file, which has just been created by running the php artisan make:migration command. You need to add the following line to the file:

$table->dropColumn('your_column_name_here');
<?php

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

class RemoveColumnFromPostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('your_column_name_here');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            //
        });
    }
}

Run the migration

php artisan migrate

Now you’re done, check your table.

Leave a reply

Your email address will not be published.