What are migrations
Migrations are like version control for your database. They let your team share and manage the application’s database schema definition. You’ve likely experienced situations where, after pulling source code, you have to tell teammates: “please manually add this column to your local database.” Migrations solve that problem. Migration files are stored in thedatabase/migrations directory.
Each file name includes a timestamp, which Laravel uses to determine the order in which migrations are run.
Creating a migration file
Generate a new migration file with themake:migration Artisan command.
create_posts_table, code to create a posts table is scaffolded for you.
Migration structure
A migration class has two methods:up and down.
upmethod: Adds tables, columns, and indexes to the database.downmethod: Reverses the operations inup. Called during rollback.
Common column definition methods
TheBlueprint class provides many column types.
Column modifiers
You can chain modifiers to a column definition.Running migrations
Use themigrate command to run all pending migrations.
migrate:status to see which migrations have and have not run.
Rollbacks
Usemigrate:rollback to undo the last batch of migrations.
--step option.
migrate:refresh.
migrate:refresh recreates all tables, so all existing data is lost.
It’s handy for resetting your database during development.Practical example: creating the posts table
Walk through the entire flow using aposts table that stores blog posts.
1. Generate the migration file
2. Edit the migration
Open and editdatabase/migrations/xxxx_xx_xx_xxxxxx_create_posts_table.php.
3. Run the migration
posts table is created in the database.
4. Adding a column later
To add new columns after a table has been created, don’t edit the existing migration—create a new migration.Migration events
An event is dispatched for each migration operation. All events extendIlluminate\Database\Events\MigrationEvent.
For example, you can listen for the
MigrationsEnded event to clear caches after migrations finish.
Next steps
Database seeding
Learn how to populate the tables created by migrations with sample data.
Eloquent introduction
Learn how to interact with the tables you created via migrations using the Eloquent ORM.