Migrations That Won’t Break Production
A migration runs perfectly on your machine. You deploy it on a Friday at 6 PM because it seems small. Then the deployment freezes. Or worse, a table with 8 million rows locks up for 40 seconds and your site crashes.
Migrations behave differently in production. Local databases are empty and fast. Production databases have real data and active users.
Follow these rules to avoid production disasters.
Always write a working down method Every migration needs an up and a down function. The down function must reverse the up function exactly. If you cannot write a rollback, your migration is too complex. Test it on your machine with migrate followed by migrate:rollback before you push.
Never edit old migrations You might want to fix a column size in an old migration file. Do not do this. Laravel will not run that file again on the server. Instead, create a new migration to change the structure. Migration is a history of changes. You add new chapters instead of rewriting old ones.
Use nullable or default values Adding a NOT NULL column to a table with existing data causes errors. The database does not know what to put in the old rows.
Use these approaches instead: • Make the new column nullable. • Set a default value. • If the column must be required, do it in three steps: create it as nullable, fill the data, then change it to NOT NULL.
Data loss is permanent The dropColumn command deletes data forever. A rollback can recreate a column, but the data inside is gone. Before you drop a column, verify your backups. A safer way is to stop using the column in your code first, wait a few weeks, and then remove it from the database.
Separate schema changes from data updates Running User::all() inside a migration can load millions of rows into memory and crash your deploy. If you must update data during a migration, use chunkById to process records in small batches.
Use the force flag in pipelines Automated deployment pipelines will hang if Laravel asks for confirmation. Use this command in your deployment scripts: php artisan migrate --force
Watch out for table locks Changing a column or adding an index on a massive table locks that table. This causes downtime. For very large tables, look into online schema change tools or run changes during low traffic hours.
Checklist before you push: • Does the down method work? • Did I test the rollback locally? • Am I creating a new migration instead of editing an old one? • Is the new column nullable or does it have a default? • Do I have a backup before dropping columns?
Source: https://dev.to/denisgusto1/migrations-que-nao-quebram-em-producao-o-guia-que-ninguem-te-deu-363o
