How to remove column in Laravel migration?

by raphael_tillman , in category: PHP Frameworks , 9 months ago

How to remove column in Laravel migration?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 3 months ago

@raphael_tillman 

To remove a column from a table using a Laravel migration, you can use the $table->dropColumn() method. Here's an example of how to use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class RemoveColumnFromTable extends Migration
{
    public function up()
    {
        Schema::table('table_name', function (Blueprint $table) {
            $table->dropColumn('column_name');
        });
    }

    public function down()
    {
        Schema::table('table_name', function (Blueprint $table) {
            $table->string('column_name')->after('another_column');
        });
    }
}


In the example above, the up method is executed when the migration is run, and the down method is executed when the migration is rolled back. In the up method, the dropColumn method is used to remove the column_name column from the table_name table. In the down method, the string method is used to add the column_name column back to the table.


To run the migration, you can use the php artisan migrate command. To roll back the migration, you can use the php artisan migrate:rollback command.


I hope this helps! Let me know if you have any questions.