Migrations & Seeding

Migrations are a type of version control for your database. They allow a team to modify the database schema and stay up to date on the current schema state. Migrations are typically paired with the Schema Builder to easily manage your application's schema.

To create a migration, you may use the command on the Artisan CLI:

The migration will be placed in your database/migrations folder, and will contain a timestamp which allows the framework to determine the order of the migrations.

  1. php artisan make:migration add_votes_to_users_table --table=users
  2. php artisan make:migration create_users_table --create=users

Running All Outstanding Migrations

  1. php artisan migrate

Some migration operations are destructive, meaning they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before these commands are executed. To force the commands to run without a prompt, use the —force flag:

Rollback The Last Migration Operation

  1. php artisan migrate:rollback

Rollback all migrations

  1. php artisan migrate:reset

Rollback all migrations and run them all again

Laravel also includes a simple way to seed your database with test data using seed classes. All seed classes are stored in database/seeds. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UserTableSeeder, etc. By default, a class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

Example Database Seed Class

  1. class DatabaseSeeder extends Seeder {
  2. public function run()
  3. {
  4. $this->call('UserTableSeeder');
  5. $this->command->info('User table seeded!');
  6. }
  7. class UserTableSeeder extends Seeder {
  8. public function run()
  9. {
  10. DB::table('users')->delete();
  11. User::create(['email' => '']);
  12. }
  13. }

To seed your database, you may use the db:seed command on the Artisan CLI:

  1. php artisan db:seed

By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the —class option to specify a specific seeder class to run individually:

You may also seed your database using the command, which will also rollback and re-run all of your migrations: