How to roll back migration in Laravel
Revert Laravel migration w/ example: Learn how to undo changes to your database tables & restore old data without deleting entire migration.
Rolling Back Migrations in Laravel
Migrations are a powerful way to manage database changes in Laravel. After a migration is run, it is possible to roll back the changes if something goes wrong. This is done using the migrate:rollback
artisan command.
For example, let's say you have an application and you have created a users
table using the following migration:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
To roll back this migration, you need to run the following command from your Laravel project root directory:
php artisan migrate:rollback
This command will reverse the changes made by the last migration executed. In this case, it will delete the users
table and all associated data.
You can also roll back multiple migrations at once by specifying the number of migrations to roll back using the --step
option:
php artisan migrate:rollback --step=5
This command will roll back the last 5 migrations that were executed. It is important to note that, when rolling back migrations, the order of operations is reversed. This means that the first migration to be rolled back will be the one that was most recently executed.
Rolling back migrations is a great way to undo changes that have gone wrong and restore the database to a previous state. It is important to be aware, however, that all data associated with the rolled back migrations will be lost, so great care should be taken when rolling back migrations.