How can I modify a migration in Laravel?
If your app is not in production and you seed your data, the best you can do is to run:
php artisan migrate:refresh --seed
This command will drop all tables and recreate them. Then it will seed the data.
If you will create additional migrations for each change during development, you'll end up with hundreds of migrations classes.
You can use the change
method, it allows you to modify some existing column types to a new type or modify the column's attributes.
For example modify a column to be nullable:
Schema::table('log_for_user', function ($table) {
$table->string('error_message')->nullable()->change();
});
But first of all you'll need the doctrine/dbal
package
composer require doctrine/dbal
You should create a new migration using command:
php artisan make:migration update_error_message_in_log_for_user_table
Then, in that created migration class, add this line, using the change
method like this:
class UpdateLogForUserTable extends Migration
{
public function up()
{
Schema::table('log_for_user', function (Blueprint $table) {
$table->string('error_message')->nullable()->change();
});
}
public function down()
{
Schema::table('log_for_user', function (Blueprint $table) {
$table->string('error_message')->change();
});
}
}
To make these changes and run the migration, use the command:
php artisan migrate
and to rollback the changes, use the command:
php artisan migrate:rollback
You may rollback a limited number of migrations by providing the step
option to the rollback command. For example, the following command will rollback the last five migrations:
php artisan migrate:rollback --step=5
See more about Modifying columns with Migration
There is one more option. Roll back the migration, edit the file, and run it again.
This is a fairly common thing to do on a local development server while you're working out the bugs in a new piece of code. Using the method from the accepted answer, you might end up with 17 migrations for creating a single table!
php artisan migrate
# realize you've made an error
php artisan migrate:rollback
# edit your migration file
php artisan migrate
The number of steps back to take can be specified on the command line if needed.
# undo the last 3 migrations
php artisan migrate:rollback --step=3
Or you can specify a particular migration that needs undoing.
# undo one specific migration
php artisan migrate:rollback --path=./database/migrations/2014_10_12_100000_create_users_table.php