Building Laravel database migrations that are good right away is hard – especially for beginners. That’s why you’d often want to make a change to your migration, only to discover that you’ve already migrated your database. Luckily, it’s very easy in Laravel to correctly rollback only your last database migration(s).
First, let’s just check which database migrations we’ve already run. To do so, run the command php artisan migration:status on the command line (make sure to navigate to the directory with your application files first). This would give you an output like this:
php artisan migrate:status+------+------------------------------------------------+-------+| Ran? | Migration | Batch |+------+------------------------------------------------+-------+| Yes | 2014_10_12_000000_create_users_table | 1 || Yes | 2014_10_12_100000_create_password_resets_table | 1 || Yes | 2019_08_19_000000_create_failed_jobs_table | 1 |+------+------------------------------------------------+-------+
How to rollback your latest Laravel database migration
In order to rollback the latest migration, you need the following command:
php artisan migrate:rollback --step=1
The command itself is very simple, but let me just explain it shortly:
- The
php artisancommand specifies that you want to use Laravel's built-in command line tool, called Artisan. This tool allows you to run commands specifically for your Laravel application. Most likely you've encountered this already before. - The part with
migrate:rollbackis the actual command. It says that you want to rollback certain database migrations. - The last part,
--step=1, is a parameter for themigrate:rollbackcommand. By default,php artisan migrate:rollbackwill rollback all of your database migrations. By specifying--step=1, you're saying that you only want to rollback the latest database migration.
Plus, if you change the number, e.g. into--step=2, you're telling Laravel to only rollback the last two migrations.
Cleaning up after rolling back a database migration
After rolling back a database migration, it's good practice to run the following command:
composer dump-autoload
This command cleans up your composer autoload file, possibly preventing errors and problems in the future.
- Published
- 29 June 2021
- Category
- Laravel