Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel migrate:rollback adding and deleting table columns

I have used the php artisan migrate:make add_something_to_to_user_table --table=users

and coded

Schema::table('users', function(Blueprint $table)
    {
        $table->string('description1');
        $table->string('description2');
        $table->string('description3');
    });

and added three fields and gave php artisan migrate and the fields got stored in to the database

also found that the migration table is updated with the row 2014_11_05_145536_add_something_to_to_user_table

now when i use php artisan migrate:rollback

The 2014_11_05_145536_add_something_to_to_user_table row in the migration table is missing but the columns added to the users table remains the same

why it is not deleting the fields in the table also which results in error while using php artisan migrate again...

like image 762
Ronser Avatar asked Dec 01 '22 01:12

Ronser


2 Answers

You should have a down() method in you migration that should look like this:

public function down()
{
    Schema::table('users', function($table)
    {
        $table->dropColumn(array('description1', 'description2', 'description3'));
    });
}

That will be called on rollback and will take care of removing the columns added by the migration.

like image 69
Bogdan Avatar answered Dec 04 '22 02:12

Bogdan


According to laravel 7+ doc this will also work when you need to drop multiple columns at the same time.

public function down(){
    Schema::table('users', function (Blueprint $table) {
     $table->dropColumn(['description1', 'description2', 'description3']);
   });
}
like image 38
ireshan pathirana Avatar answered Dec 04 '22 02:12

ireshan pathirana