0
0
Laravelframework~15 mins

Running and rolling back migrations in Laravel - Deep Dive

Choose your learning style9 modes available
Overview - Running and rolling back migrations
What is it?
Running and rolling back migrations in Laravel means applying or undoing changes to your database structure using special scripts called migrations. These migrations let you create, modify, or delete tables and columns in a safe and organized way. Running migrations updates your database to the latest structure, while rolling back reverses recent changes if needed. This helps keep your database in sync with your application code.
Why it matters
Without migrations, managing database changes would be chaotic and error-prone, especially when working with a team or deploying updates. You might lose data or have inconsistent database structures across environments. Migrations provide a clear history of changes and a simple way to apply or undo them, making development smoother and safer.
Where it fits
Before learning migrations, you should understand basic databases and Laravel's artisan command-line tool. After mastering running and rolling back migrations, you can learn about seeding databases with test data and advanced migration features like modifying existing tables or handling complex schema changes.
Mental Model
Core Idea
Migrations are like step-by-step instructions for changing your database, and running or rolling back them applies or undoes those steps to keep your database structure in sync with your code.
Think of it like...
Imagine building a LEGO model with instructions. Running migrations is like following the steps to add new pieces, while rolling back is like undoing the last steps to remove pieces if you made a mistake.
┌───────────────┐       run       ┌───────────────┐
│ Migration 1  │ ─────────────▶ │ Database v1   │
├───────────────┤                ├───────────────┤
│ Migration 2  │ ─────────────▶ │ Database v2   │
├───────────────┤                ├───────────────┤
│ Migration 3  │ ─────────────▶ │ Database v3   │
└───────────────┘                └───────────────┘

Rollback:

┌───────────────┐       rollback   ┌───────────────┐
│ Migration 3  │ ◀───────────── │ Database v3   │
├───────────────┤                ├───────────────┤
│ Migration 2  │ ◀───────────── │ Database v2   │
└───────────────┘                └───────────────┘
Build-Up - 6 Steps
1
FoundationWhat are Laravel migrations?
🤔
Concept: Introduce migrations as version-controlled scripts for database changes.
Migrations in Laravel are PHP files that describe how to create or change database tables. Each migration has two main parts: 'up' to apply changes and 'down' to undo them. Laravel uses these files to keep track of your database structure over time.
Result
You understand migrations as organized instructions for database changes.
Understanding migrations as code files helps you see database changes as part of your application, not separate manual steps.
2
FoundationRunning migrations with artisan
🤔
Concept: Learn how to apply migrations to update the database.
Using the command 'php artisan migrate', Laravel runs all pending migrations in order. This creates or modifies tables as defined. Laravel records which migrations have run in a special table to avoid repeating them.
Result
Your database structure updates to the latest version defined by migrations.
Knowing that Laravel tracks migrations prevents accidental duplicate changes and keeps your database consistent.
3
IntermediateRolling back migrations safely
🤔Before reading on: do you think rolling back removes all migrations or just the last batch? Commit to your answer.
Concept: Learn how to undo recent migrations to revert database changes.
The command 'php artisan migrate:rollback' undoes the last batch of migrations that were run together. This calls the 'down' method in those migration files to reverse changes. You can rollback multiple batches by adding the '--step' option.
Result
Your database structure reverts to a previous state by undoing recent changes.
Understanding rollback batches helps you control how far back you undo changes without affecting unrelated migrations.
4
IntermediateResetting and refreshing migrations
🤔Before reading on: do you think 'migrate:reset' and 'migrate:refresh' do the same thing? Commit to your answer.
Concept: Explore commands to undo all migrations or rollback then re-run them.
'php artisan migrate:reset' rolls back all migrations, clearing the database structure. 'php artisan migrate:refresh' rolls back all migrations and then runs them again, useful for rebuilding the database from scratch during development.
Result
You can completely undo or rebuild your database structure quickly.
Knowing these commands speeds up development by letting you start fresh without manual database cleanup.
5
AdvancedHandling migration dependencies and order
🤔Before reading on: do you think migration order is automatic or must be managed carefully? Commit to your answer.
Concept: Understand how Laravel orders migrations and why order matters.
Laravel runs migrations in the order of their timestamp prefix in filenames. This ensures dependencies like creating tables before adding columns work correctly. If order is wrong, migrations can fail or cause errors.
Result
You can organize migrations to avoid conflicts and errors during runs.
Recognizing the importance of migration order prevents frustrating bugs and data loss in real projects.
6
ExpertSurprising rollback behavior and pitfalls
🤔Before reading on: do you think rolling back a migration always restores data perfectly? Commit to your answer.
Concept: Discover limitations and unexpected effects of rolling back migrations.
Rolling back migrations only reverses schema changes, not data changes inside tables. For example, dropping a column deletes its data permanently. Also, rolling back migrations that affect foreign keys can cause errors if dependent tables exist. Careful planning and backups are needed.
Result
You avoid data loss and errors by understanding rollback limits.
Knowing rollback only affects structure, not data, helps you plan safer database changes and backups.
Under the Hood
Laravel stores migration files with timestamps to order them. When you run 'php artisan migrate', Laravel checks a special 'migrations' table in the database to see which migrations have run. It then executes the 'up' method of new migrations in order and records them. Rolling back runs the 'down' method of the last batch and removes their records. This tracking ensures migrations run only once and can be reversed in batches.
Why designed this way?
This design allows teams to share database changes as code, ensuring everyone applies the same updates in the same order. The timestamp naming avoids conflicts and ordering issues. Tracking migrations in the database prevents duplicate runs and supports safe rollbacks. Alternatives like manual SQL scripts lack this automation and safety.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Migration 1  │──────▶│ migrations    │──────▶│ Database      │
│ (timestamp)  │       │ table records │       │ schema change │
├───────────────┤       └───────────────┘       └───────────────┘
│ Migration 2  │
├───────────────┤
│ Migration 3  │
└───────────────┘

Rollback:

┌───────────────┐◀─────┐
│ Migration 3  │      │
│ down() runs │      │
└───────────────┘      │
                       │
┌───────────────┐      │
│ migrations    │◀─────┘
│ table updated │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does rolling back a migration restore deleted data automatically? Commit to yes or no.
Common Belief:Rolling back a migration will restore any data that was deleted when the migration ran.
Tap to reveal reality
Reality:Rolling back only reverses schema changes; it does not restore deleted data inside tables.
Why it matters:Assuming data is restored can cause unexpected data loss and bugs in your application.
Quick: Can you run migrations in any order without problems? Commit to yes or no.
Common Belief:Migrations can be run in any order because Laravel will handle dependencies automatically.
Tap to reveal reality
Reality:Migrations must be run in timestamp order to maintain dependencies; running out of order can cause errors.
Why it matters:Ignoring order can break your database schema and cause migration failures.
Quick: Does 'migrate:rollback' undo all migrations by default? Commit to yes or no.
Common Belief:'migrate:rollback' always rolls back all migrations to the initial state.
Tap to reveal reality
Reality:'migrate:rollback' only rolls back the last batch of migrations run together, not all migrations.
Why it matters:Misunderstanding rollback scope can lead to partial undos and confusion about database state.
Quick: Is it safe to run 'migrate:refresh' on a production database? Commit to yes or no.
Common Belief:'migrate:refresh' is safe to run anytime because it just updates the database schema.
Tap to reveal reality
Reality:'migrate:refresh' drops all tables and rebuilds them, causing complete data loss if run on production.
Why it matters:Running refresh on production can cause catastrophic data loss.
Expert Zone
1
Laravel batches migrations by grouping those run in a single command, enabling partial rollbacks instead of undoing all changes.
2
The 'down' method in migrations is optional but highly recommended; missing it means rollbacks cannot undo changes safely.
3
Foreign key constraints require careful ordering and sometimes manual disabling during rollbacks to avoid errors.
When NOT to use
Avoid running 'migrate:refresh' or 'migrate:reset' on production databases because they drop all tables and data. Instead, use incremental migrations with careful testing. For complex schema changes, consider using database-specific tools or manual SQL scripts alongside migrations.
Production Patterns
In production, teams use incremental migrations with thorough testing and backups. Rollbacks are used cautiously, often only for the last batch. Continuous integration pipelines run migrations automatically during deployment. Some teams write migrations to be backward compatible to avoid downtime.
Connections
Version Control Systems (e.g., Git)
Migrations are like version control for databases, tracking changes over time.
Understanding migrations as database version control helps grasp their role in collaboration and history tracking.
Transaction Management in Databases
Rolling back migrations conceptually relates to database transactions that can be committed or rolled back.
Knowing how transactions work clarifies why some migration rollbacks can fail if dependencies or constraints exist.
Undo/Redo Functionality in Text Editors
Rolling back migrations is similar to undoing recent changes in a document editor.
This connection highlights the importance of reversible steps and history tracking in software systems.
Common Pitfalls
#1Running 'php artisan migrate:refresh' on a live database causing data loss.
Wrong approach:php artisan migrate:refresh
Correct approach:php artisan migrate
Root cause:Misunderstanding that 'refresh' drops all tables and rebuilds them, which is unsafe for production.
#2Writing migrations without a 'down' method, making rollbacks impossible.
Wrong approach:public function down() { /* empty or missing */ }
Correct approach:public function down() { Schema::dropIfExists('table_name'); }
Root cause:Not realizing rollbacks rely on the 'down' method to reverse changes.
#3Changing migration filenames to reorder them after they have run.
Wrong approach:Renaming migration files to change timestamps after running them.
Correct approach:Create new migrations for changes instead of renaming old ones.
Root cause:Believing migration order can be changed by renaming files, ignoring Laravel's tracking.
Key Takeaways
Migrations are code files that safely manage database structure changes over time.
Running migrations applies new changes; rolling back undoes recent changes in batches.
Laravel tracks which migrations have run to avoid duplicates and maintain order.
Rollback only reverses schema changes, not data inside tables, so data loss can occur.
Commands like migrate:refresh are powerful but dangerous on production and should be used carefully.