hamza-wakrim / laravel-safe-migrations
Catch dangerous Laravel migrations (dropped or renamed columns, blocking indexes, NOT NULL columns without defaults...) before they reach production.
Package info
github.com/Hamza-Wakrim/laravel-safe-migrations
pkg:composer/hamza-wakrim/laravel-safe-migrations
Requires
- php: ^8.2
- illuminate/console: ^12.0|^13.0
- illuminate/database: ^12.0|^13.0
- illuminate/support: ^12.0|^13.0
- nikic/php-parser: ^5.0
Requires (Dev)
- larastan/larastan: ^3.0
- orchestra/testbench: ^10.0|^11.0
- phpunit/phpunit: ^11.0|^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Find dangerous migrations before they reach production.
Some migrations look harmless but take your app down when they run on a busy production database:
- dropping or renaming a column that the old code (still running during the deploy) is reading,
- adding a
NOT NULLcolumn to a table that already has rows, - building an index on PostgreSQL, which blocks every write to the table until it finishes,
- adding a foreign key on MySQL, which copies the whole table and blocks writes while it does,
- using
CREATE INDEX CONCURRENTLYin a migration that runs inside a transaction, which PostgreSQL rejects, - an
UPDATEwithout aWHEREthat rewrites millions of rows in one transaction, - a
down()that would destroy data if you have to roll back in a hurry.
This package finds those problems before you run migrate. It dry-runs your pending migrations (both up() and down()), looks at the SQL they would execute and at the PHP code itself, and tells you what is risky, why, and how to do it safely.
2024_02_01_000000_drop_legacy_from_users
ERROR [drop-column] Dropping column [users.legacy] destroys its data, and app servers still running the old code will fail on queries that use it.
alter table "users" drop column "legacy"
→ Remove every use of the column from the code and deploy that first, then drop the column in a follow-up migration.
2024_04_01_000000_backfill_names
WARN [data-mutation] Updating [users] without a WHERE clause rewrites every row in one long transaction.
update "users" set "name" = 'unknown'
→ Move data changes into a queued job or command that works in batches, and keep migrations for schema changes.
ERROR Checked 2 migration(s): 1 error(s), 1 warning(s).
The check never changes your database. It doesn't create tables, add columns or even the migrations table, on any of your connections. Code that tries to bypass Laravel and talk to the database directly is blocked, not run.
Your
up()anddown()code still runs. Database statements are recorded instead of executed, and Laravel's HTTP client, mail, notifications, queue, jobs, events, cache, storage, processes andArtisan::call()are swapped for fakes during the check, so those don't happen either. Plain PHP that doesn't go through Laravel, likefile_put_contents()orcurl, really runs. Keep migrations to database changes. See Limitations.
Try it in 30 seconds:
composer require hamza-wakrim/laravel-safe-migrations php artisan safe-migrations:check
Using 1.0.0 or 1.0.1? Please upgrade to the latest version. In those versions the dry run could run statements for real when a migration used a second database connection or sent SQL straight to PDO.
Contents
- How it works
- Requirements
- Installation
- Quick start
- The three ways to use it
- Errors vs. warnings
- When a finding is intentional
- Rules and how to fix each one
- Configuration reference
- Command reference
- JSON output
- FAQ
- Limitations
- Troubleshooting
- Developing this package
- Contributing
How it works
- It finds the migrations that have not run yet on the database you point it at (the same list
php artisan migrate:statusshows as Pending). - It runs each one in Laravel's pretend mode. Nothing is written to the database; Laravel only records the SQL it would run.
- Each SQL statement is checked against a set of rules.
- It does the same for
down(), to see what a rollback would break (unsafe-rollback). - It also reads the PHP source of
up(), to find what a dry run can't show: branches onSchema::hasColumn()that were skipped, and code that reads rows (schema-condition,reads-data). - Every problem is reported with the migration name, the SQL, an explanation and a suggested fix.
Because it checks the SQL your migration actually runs, it also catches DB::statement(...), DB::table(...)->update(...) and anything else your migration executes.
Tables that are created in the same batch of pending migrations are never flagged. They hold no production data yet, so adding indexes or dropping columns on them is harmless.
Every configured database connection is in pretend mode during the check, so a migration that also uses Schema::connection('analytics') or DB::connection('tenant') is analysed too, and nothing runs on those databases either.
Raw SQL
Raw queries are checked the same way as schema builder calls, because the rules read the SQL:
| In your migration | What happens |
|---|---|
DB::statement('ALTER TABLE users DROP COLUMN x') |
Checked like any other statement (here: drop-column) |
DB::unprepared('...; ...; ...') |
Split into separate statements, and each one is checked |
DB::table('users')->update(['x' => DB::raw('...')]) |
Checked (here: data-mutation if there is no WHERE) |
DB::getPdo()->exec('...') or other direct PDO calls |
Blocked, never executed, and reported as analysis-failed so you review it by hand |
PostgreSQL function bodies ($$ ... $$) are kept whole, so statements inside a CREATE FUNCTION are not reported as if they ran during the migration.
SQL comments (-- ... and /* ... */) are ignored, so a comment before or inside a statement cannot hide it from the check, and a commented-out statement is not reported. Comment markers inside quoted strings are left alone, and MySQL executable comments (/*!40000 ... */) are checked as SQL, because MySQL runs them.
Requirements
- PHP 8.2 or newer (8.3 or newer for Laravel 13)
- Laravel 12 or 13
- MySQL, MariaDB, PostgreSQL or SQLite (SQL Server is not supported)
MariaDB works with Laravel's mariadb driver and with the mysql driver: a MariaDB server is detected either way and checked with MariaDB's rules, since its online DDL differs from MySQL's.
Installation
From Packagist
composer require hamza-wakrim/laravel-safe-migrations
From a local folder (for development)
In your Laravel app's composer.json, add a path repository pointing at this folder:
"repositories": [ { "type": "path", "url": "../laravel-safe-migrations" } ]
Then install it:
composer require hamza-wakrim/laravel-safe-migrations:@dev
Publish the config (optional)
The service provider registers itself automatically. Publish the config file only if you want to change rules or turn on the guard:
php artisan vendor:publish --tag=safe-migrations-config
This creates config/safe-migrations.php.
Upgrading
Within 1.x there are no breaking changes, so updating is one command:
composer update hamza-wakrim/laravel-safe-migrations
If you published the config file, you can optionally add the rules added since 1.0.0 to its rules array:
'analysis-failed' => null, // new in 1.0.2, warning 'concurrent-in-transaction' => null, // new in 1.1.0, error (PostgreSQL) 'lock-timeout' => null, // new in 1.2.0, off until you set 'warning' or 'error' 'unsafe-rollback' => null, // new in 1.3.0, warning 'missing-down' => null, // new in 1.3.0, off until you set 'warning' or 'error' 'schema-condition' => null, // new in 1.3.0, warning 'reads-data' => null, // new in 1.3.0, warning 'table-copy' => null, // new in 1.4.0, warning (MySQL, MariaDB) 'unsupported-algorithm' => null, // new in 1.4.0, error (MySQL, MariaDB)
Without them each rule keeps its default severity.
See the changelog for what changed in each version.
Quick start
-
Install the package (see above).
-
Create a migration that drops a column:
php artisan make:migration drop_nickname_from_users
public function up(): void { Schema::table('users', function (Blueprint $table) { $table->dropColumn('nickname'); }); }
-
Check it:
php artisan safe-migrations:check
You get an
ERROR [drop-column]with an explanation and the command exits with code1. -
Decide what to do:
- Fix it: follow the suggestion (for example, ship the code that stops using the column first, drop it in a later release).
- Accept it: you have checked that nothing uses the column any more, so mark the migration with
#[AllowUnsafe]. - Run it once anyway:
php artisan migrate:safe --unsafe.
The three ways to use it
Use one, two or all three. Most teams use A and B together.
A. Check before you merge (CI)
Run the check on every pull request so unsafe migrations are caught in review.
php artisan safe-migrations:check
It exits with 0 when everything is safe and 1 when there are errors, so a failing check fails the CI job.
Important: the check only looks at migrations that have not run yet. In CI, the database must already have your existing migrations applied, so that only the new migrations from the pull request are checked. If you check against an empty database, every table is "created in this run" and almost nothing gets flagged.
The usual way to do that is to migrate the database with your main branch first, then check the pull request:
# .github/workflows/safe-migrations.yml (example) name: Safe migrations on: pull_request jobs: check: runs-on: ubuntu-latest services: postgres: image: postgres:17 env: POSTGRES_DB: app POSTGRES_USER: app POSTGRES_PASSWORD: secret ports: ["5432:5432"] options: --health-cmd pg_isready --health-interval 5s --health-retries 10 env: DB_CONNECTION: pgsql DB_HOST: 127.0.0.1 DB_DATABASE: app DB_USERNAME: app DB_PASSWORD: secret steps: # 1. Apply the migrations that are already on the main branch. - uses: actions/checkout@v5 with: ref: ${{ github.base_ref }} - uses: shivammathur/setup-php@v2 with: php-version: "8.3" - run: cp .env.example .env && composer install --no-interaction && php artisan key:generate - run: php artisan migrate --force # 2. Switch to the pull request and check only its new migrations. - uses: actions/checkout@v5 with: clean: false - run: composer install --no-interaction - run: php artisan safe-migrations:check
Use the same database engine as production in CI (PostgreSQL if you run PostgreSQL). Several rules only apply to one engine because the locking behaviour is different.
B. migrate:safe in your deploy script
Replace php artisan migrate --force in your deploy script (Forge, Envoyer, Deployer, a shell script...) with:
php artisan migrate:safe --force
It checks the pending migrations against the real production database first:
- Nothing unsafe: it runs
migrateas usual. - Errors found: it prints the report, does not migrate, and exits with
1, which stops the deploy.
migrate:safe accepts the usual migrate options (--database, --path, --realpath, --force, --step, --seed) plus:
| Option | Effect |
|---|---|
--strict |
Also refuse to migrate when there are only warnings |
--unsafe |
Print the report but migrate anyway. Use this for a one-off run after you reviewed the findings |
C. Guard the plain migrate command
If people or tools run php artisan migrate directly, you can make that command refuse unsafe migrations too.
In .env on the server:
SAFE_MIGRATIONS_GUARD=true
Now in the environments listed in guard.environments (default: production), php artisan migrate stops before running anything if a pending migration has errors:
Refusing to migrate: 1 unsafe operation(s) found in pending migrations.
- [drop-column] 2024_02_01_000000_drop_legacy_from_users: Dropping column [users.legacy] ...
Notes:
migrate --pretendis never blocked.migrate:safe --unsafestill works with the guard on, so that is the way to run a reviewed migration once.- To switch the guard off without a deploy, set
SAFE_MIGRATIONS_ALLOW_UNSAFE=truein.envand runphp artisan config:clear(orconfig:cache). Remember to remove it again.
Errors vs. warnings
| Meaning | Blocks check / migrate:safe / guard? |
|
|---|---|---|
| ERROR | Almost always breaks something: lost data, failing queries from the running code, or a migration that fails when it runs in production (on a non-empty table, or because the database rejects the statement). | Yes |
| WARN | Can lock a table or be slow, depending on table size and database version. Worth a look. | Only with --strict (or guard.strict) |
You can change the severity of any rule, or switch it off, in the config.
When a finding is intentional
Sometimes you really do want to drop that column. Mark the migration with the AllowUnsafe attribute so the decision is written down next to the code and visible in code review:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use HamzaWakrim\SafeMigrations\Attributes\AllowUnsafe; return new #[AllowUnsafe('drop-column', reason: 'nickname has not been used since v2.3')] class extends Migration { public function up(): void { Schema::table('users', function (Blueprint $table) { $table->dropColumn('nickname'); }); } };
- Allow several rules:
#[AllowUnsafe(['drop-column', 'drop-table'])] - Allow everything in this migration:
#[AllowUnsafe] - Named (non-anonymous) migration classes work the same way: put the attribute above
class ... extends Migration.
Allowed findings don't fail the check. The summary still counts them (1 allowed by #[AllowUnsafe]), and they appear under suppressed in the JSON output.
To skip a migration completely (for example, an old one you don't want to touch), add its file name without .php to ignore_migrations in the config.
Rules and how to fix each one
| Rule | Default | Databases |
|---|---|---|
drop-table |
error | all |
drop-column |
error | all |
rename-table |
error | all |
rename-column |
error | all |
add-not-null-column |
error (warning on MySQL / MariaDB) | all |
change-column |
warning | MySQL, MariaDB, PostgreSQL |
set-not-null |
warning | PostgreSQL |
blocking-index |
warning | PostgreSQL |
concurrent-in-transaction |
error | PostgreSQL |
blocking-foreign-key |
warning | PostgreSQL |
table-rebuild |
warning | SQLite |
table-copy |
warning | MySQL, MariaDB |
unsupported-algorithm |
error | MySQL, MariaDB |
data-mutation |
warning | all |
lock-timeout |
off (opt-in) | MySQL, MariaDB, PostgreSQL |
unsafe-rollback |
warning | all |
missing-down |
off (opt-in) | all |
schema-condition |
warning | all (reads PHP) |
reads-data |
warning | all (reads PHP) |
analysis-failed |
warning | all |
Most fixes follow the same idea, sometimes called expand / contract: never remove or change something the running code depends on in the same deploy. Add the new thing, deploy code that uses it, and remove the old thing in a later release.
drop-table
Flags: Schema::drop() / Schema::dropIfExists() on an existing table.
Why: the data is gone, and during the deploy the old code is still running and querying the table.
Safe way:
- Deploy code that no longer reads or writes the table.
- Back up the table if you might need the data.
- Drop it in a migration in a later release, marked with
#[AllowUnsafe('drop-table', reason: '...')].
drop-column
Flags: $table->dropColumn(...) on an existing table.
Why: Eloquent's select * and any code still using the column fail between the moment the migration runs and the moment the new code is live.
Safe way:
- Remove every use of the column from the code (models, queries, validation, API resources) and deploy.
- In the next release, drop the column with
#[AllowUnsafe('drop-column', reason: '...')].
rename-table and rename-column
Flags: Schema::rename(), $table->renameColumn().
Why: the code that is running during the deploy still uses the old name.
Safe way (for a column):
- Add the new column (nullable).
- Write to both columns in the code; backfill the new column in batches.
- Switch reads to the new column and deploy.
- Drop the old column in a later release.
Or keep the database name and change only the PHP side (an Eloquent accessor, or an API resource field name).
add-not-null-column
Flags: adding a column that is NOT NULL and has no default.
$table->string('timezone'); // flagged: NOT NULL, no default
Why: PostgreSQL and SQLite refuse to add it as soon as the table has rows, so the migration fails in production even though it worked on your empty local database. MySQL and MariaDB add it but silently fill existing rows with '', 0 or a zero date, which is why this rule is only a warning there.
Safe way: either give it a default:
$table->string('timezone')->default('UTC');
or do it in steps:
// Migration 1 $table->string('timezone')->nullable(); // Backfill the existing rows (a job or command, in batches) // Migration 2 (later release) $table->string('timezone')->nullable(false)->change();
On PostgreSQL, migration 2 is reported as change-column and set-not-null warnings. See set-not-null for the lock-free version.
change-column
Flags: ->change() and other column type changes (MODIFY / CHANGE on MySQL and MariaDB, ALTER COLUMN ... TYPE on PostgreSQL).
Why: many type changes make the database rewrite the whole table while holding a lock, blocking reads and writes. On a big table that can take minutes.
Safe way: check your database's documentation for that specific change (some, such as making a varchar longer on PostgreSQL, are instant). For a big table, add a new column, backfill it in batches and swap. If you have checked that it is fine, add #[AllowUnsafe('change-column')].
set-not-null
Flags (PostgreSQL): making an existing column NOT NULL, for example ->nullable(false)->change().
Why: PostgreSQL scans the whole table to make sure there are no NULLs, under a lock that blocks reads and writes.
Safe way (PostgreSQL 12+): prove there are no NULLs first with a constraint that is validated without the heavy lock:
// Migration 1 DB::statement('ALTER TABLE users ADD CONSTRAINT users_timezone_not_null CHECK (timezone IS NOT NULL) NOT VALID'); // Migration 2 DB::statement('ALTER TABLE users VALIDATE CONSTRAINT users_timezone_not_null'); // Migration 3: PostgreSQL uses the validated constraint and skips the scan DB::statement('ALTER TABLE users ALTER COLUMN timezone SET NOT NULL'); DB::statement('ALTER TABLE users DROP CONSTRAINT users_timezone_not_null');
The checker cannot tell that step 3 is now cheap, so mark migration 3 with #[AllowUnsafe('set-not-null')].
blocking-index
Flags (PostgreSQL): $table->index(), $table->unique() and $table->primary() on an existing table.
Why: a normal CREATE INDEX blocks every INSERT, UPDATE and DELETE on the table until the index is built.
Safe way: build it with CONCURRENTLY. That cannot run inside a transaction, so turn the migration's transaction off:
return new class extends Migration { public $withinTransaction = false; public function up(): void { DB::statement('CREATE INDEX CONCURRENTLY users_email_index ON users (email)'); } public function down(): void { DB::statement('DROP INDEX CONCURRENTLY IF EXISTS users_email_index'); } };
For a unique constraint, build the unique index concurrently, then attach it:
DB::statement('CREATE UNIQUE INDEX CONCURRENTLY users_email_unique ON users (email)'); DB::statement('ALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE USING INDEX users_email_unique');
On MySQL (InnoDB), adding a normal index is an online operation, so this rule does not apply.
concurrent-in-transaction
Flags (PostgreSQL): CREATE INDEX CONCURRENTLY, DROP INDEX CONCURRENTLY, REINDEX ... CONCURRENTLY and DETACH PARTITION ... CONCURRENTLY in a migration that runs inside a transaction (the default on PostgreSQL).
Why: PostgreSQL refuses to run these inside a transaction block, so the migration fails in production. It is easy to miss because the same migration passes on MySQL, which never wraps migrations in a transaction.
Safe way: turn the migration's transaction off, and keep the concurrent statement in a migration of its own (without a transaction, a failure halfway leaves the earlier statements applied):
return new class extends Migration { public $withinTransaction = false; public function up(): void { DB::statement('CREATE INDEX CONCURRENTLY users_email_index ON users (email)'); } };
blocking-foreign-key
Flags (PostgreSQL): $table->foreign(...) / ->constrained() on an existing table.
Why: PostgreSQL checks every existing row while blocking writes on both tables.
Safe way: add the constraint without checking old rows, then validate it separately (validation only takes a light lock):
// Migration 1 DB::statement('ALTER TABLE posts ADD CONSTRAINT posts_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) NOT VALID'); // Migration 2 DB::statement('ALTER TABLE posts VALIDATE CONSTRAINT posts_user_id_foreign');
table-rebuild
Flags (SQLite): operations SQLite cannot do in place (such as ->change()), which Laravel performs by copying the whole table into a new one.
Why: the database is locked while every row is copied. That's fine for small tables and slow for big ones.
Safe way: usually nothing. Just be aware of it on large SQLite databases.
table-copy
Flags (MySQL, MariaDB): an ALTER TABLE on an existing table that copies the whole table (ALGORITHM=COPY) or can't run with LOCK=NONE:
| Operation | Why |
|---|---|
Adding a foreign key (->constrained(), ->foreign()) |
With foreign_key_checks on, only ALGORITHM=COPY is possible |
Adding a STORED / PERSISTENT generated column (->storedAs()) |
Always a table copy |
CONVERT TO CHARACTER SET |
Always a table copy |
| Dropping the primary key without adding a new one in the same statement | Always a table copy |
ALGORITHM=COPY written in the statement |
Asks for a copy |
Adding a FULLTEXT or SPATIAL index, or an AUTO_INCREMENT column |
Can't run with LOCK=NONE |
Everything else Laravel generates (adding and dropping columns, plain indexes, renames) runs INSTANT or in place while writes go on, so it is not reported. Column type changes are reported by change-column.
Why: on MySQL, writes to the table are blocked until the copy finishes. On a large table that is minutes of downtime. On MariaDB the answer depends on the version: before 11.2 writes are blocked; from 11.2 MariaDB can copy with LOCK=NONE, so writes go on, but the copy still takes time, double the disk space and causes replication lag.
Safe way:
// Foreign key: with checks off, MySQL and MariaDB add it in place, without a copy. // Existing rows are not validated then, so make sure they are valid first. Schema::withoutForeignKeyConstraints(function () { Schema::table('posts', fn (Blueprint $table) => $table->foreignId('team_id')->nullable()->constrained()); }); // Generated column: VIRTUAL is instant, STORED copies the table. $table->string('full_name')->virtualAs("concat(first_name, ' ', last_name)");
For the rest (character set conversion, FULLTEXT on a large table), use an online schema change tool such as gh-ost or pt-online-schema-change, or a maintenance window.
To make sure a raw ALTER never copies silently, ask for the algorithm and lock you expect. The server then refuses the statement instead of copying, and this rule doesn't report it:
DB::statement('ALTER TABLE users ADD INDEX users_email_index (email), ALGORITHM=INPLACE, LOCK=NONE'); // MySQL DB::statement('ALTER TABLE users ADD INDEX users_email_index (email), ALGORITHM=NOCOPY, LOCK=NONE'); // MariaDB
A MariaDB server behind Laravel's mysql driver is detected and checked as MariaDB.
unsupported-algorithm
Flags (MySQL, MariaDB): an ALGORITHM= or LOCK= in the statement that the operation can't use, so the server rejects it and the migration fails in production:
| Asked for | Rejected for |
|---|---|
ALGORITHM=INSTANT |
adding any index or primary key, dropping the primary key, foreign keys, character set conversion, engine changes, AUTO_INCREMENT and STORED columns |
ALGORITHM=INPLACE |
the table copies listed under table-copy |
ALGORITHM=NOCOPY (MariaDB) |
adding or dropping the primary key, character set conversion, AUTO_INCREMENT and STORED columns, foreign keys with checks on |
LOCK=NONE (MySQL only) |
everything listed under table-copy |
DB::statement('ALTER TABLE users ADD INDEX users_email (email), ALGORITHM=INSTANT'); // flagged: indexes are never instant
LOCK=NONE is only checked on MySQL: MariaDB 11.2+ accepts it for table copies, so on MariaDB the answer depends on the server version. These combinations are tested against real MySQL 8.4 and MariaDB 11.4 servers.
Safe way: remove the option, or move that operation to an ALTER TABLE of its own without it.
data-mutation
Flags: UPDATE or DELETE without a WHERE clause, and TRUNCATE, on existing tables.
DB::table('users')->update(['newsletter' => false]); // flagged
Why: one statement that touches every row holds locks for a long time, bloats the transaction log, and can time out your deploy.
Safe way: move data changes out of the migration into a command or queued job that works in chunks:
User::query()->whereNull('newsletter')->chunkById(1000, function ($users) { User::whereKey($users->modelKeys())->update(['newsletter' => false]); });
lock-timeout
Off by default. Laravel never sets a lock timeout, so this rule would flag almost every ALTER. Turn it on with 'lock-timeout' => 'warning' (or 'error').
Flags: ALTER TABLE, CREATE INDEX (without CONCURRENTLY) and RENAME TABLE on an existing table, in a migration that did not set a lock timeout first.
Why: every ALTER needs a lock on the table, even an INSTANT one on MySQL or MariaDB. If a slow query or an open transaction is using the table, the ALTER waits for it, and every query that arrives after the ALTER waits behind it. The table is effectively down until the slow query ends. With a timeout, the ALTER gives up after a few seconds instead, and you retry the deploy.
Safe way: set a timeout at the start of up().
// PostgreSQL DB::statement("SET lock_timeout = '5s'"); // MySQL / MariaDB DB::statement('SET SESSION lock_wait_timeout = 5'); Schema::table('users', function (Blueprint $table) { $table->string('nickname')->nullable(); });
On MariaDB you can also put the timeout on the statement itself: ALTER TABLE users WAIT 5 ..., ALTER TABLE users NOWAIT ..., or SET STATEMENT lock_wait_timeout=5 FOR ALTER TABLE .... A timeout of 0 on PostgreSQL means "wait forever", so it doesn't count. The timeout only counts in the migration that sets it.
If you already set the timeout for every connection (in the database config or on the server), leave this rule off.
unsafe-rollback
Flags: a down() that would do something the rules flag, on a table or column that existed before up(). Undoing what up() itself added (dropping a column or table it created) is expected and not reported.
public function up(): void { Schema::table('users', fn (Blueprint $table) => $table->string('nickname')->nullable()); } public function down(): void { // nickname is fine (up() added it), legacy is flagged: its data is lost on rollback Schema::table('users', fn (Blueprint $table) => $table->dropColumn(['nickname', 'legacy'])); }
Why: a rollback usually happens in a hurry, when something is already wrong. A down() that drops old data, renames columns back while new code is running, or adds a NOT NULL column without a default makes the incident worse.
Safe way: make down() undo exactly what up() did, nothing more. The finding shows the rule that matched (for example On rollback (drop-column): ...) and that rule's fix. To allow it, use #[AllowUnsafe('unsafe-rollback')].
missing-down
Off by default. Turn it on with 'missing-down' => 'warning'.
Flags: a migration whose up() changes the database but which has no down(), or a down() that does nothing, so migrate:rollback silently skips it.
Safe way: write a down() that undoes up(). If the migration really can't be undone, throw an exception in down() so a rollback stops with a clear message; a down() that throws is not reported.
schema-condition
Flags: up() code that branches on Schema::hasTable(), hasColumn(), hasColumns(), hasIndex() or hasView(), when the branch the check skipped contains code.
if (Schema::hasColumn('users', 'legacy')) { // flagged: this branch is never checked Schema::table('users', fn (Blueprint $table) => $table->dropColumn('legacy')); } if (! Schema::hasColumn('users', 'nickname')) { // fine: this is the branch that gets checked Schema::table('users', fn (Blueprint $table) => $table->string('nickname')->nullable()); }
Why: in pretend mode these checks always answer false, so the dry run only follows one branch. Whatever is on the other branch (here a dropped column) runs in production without being checked. An early return; on the skipped branch is not reported.
Safe way: review the skipped branch by hand, or make the migration do the same thing on every database so it doesn't need to branch.
reads-data
Flags: up() code that reads rows: DB::table(...)->get(), first(), pluck(), count(), chunk(), each(), cursor() and similar, DB::select(), and Eloquent model queries such as User::all() or User::where(...)->get().
foreach (DB::table('users')->whereNull('timezone')->get() as $user) { // flagged DB::table('users')->where('id', $user->id)->update(['timezone' => 'UTC']); }
Why: the dry run gets no rows back, so whatever the migration does per row was never checked. In production the loop runs for every row, inside the migration, while the deploy waits.
Safe way: move data changes to a command or queued job that works in batches, and keep the migration for schema changes.
analysis-failed
Flags: a migration that throws an error during the dry run, usually because it reads data first (pretend mode returns no rows), for example DB::table('settings')->first()->value.
Why: the checker could not see what the migration would do, so it can't tell you whether it is safe.
Safe way: review the migration by hand. If you are happy with it, mark it with #[AllowUnsafe('analysis-failed')].
Configuration reference
After publishing, config/safe-migrations.php contains:
return [ // null = the rule's default severity, 'error' / 'warning' = override, false = rule off 'rules' => [ 'drop-table' => null, 'drop-column' => null, 'rename-table' => null, 'rename-column' => null, 'add-not-null-column' => null, 'change-column' => null, 'set-not-null' => null, 'blocking-index' => null, 'concurrent-in-transaction' => null, 'blocking-foreign-key' => null, 'table-rebuild' => null, 'table-copy' => null, 'unsupported-algorithm' => null, 'data-mutation' => null, 'analysis-failed' => null, 'lock-timeout' => null, // off unless set to 'warning' or 'error' 'unsafe-rollback' => null, 'missing-down' => null, // off unless set to 'warning' or 'error' 'schema-condition' => null, 'reads-data' => null, ], // Migration names (file name without .php) that are never checked 'ignore_migrations' => [], 'guard' => [ 'enabled' => env('SAFE_MIGRATIONS_GUARD', false), // guard `php artisan migrate` 'environments' => ['production'], // where the guard is active 'strict' => env('SAFE_MIGRATIONS_STRICT', false), // block on warnings too 'allow_unsafe' => env('SAFE_MIGRATIONS_ALLOW_UNSAFE', false), // temporarily switch the guard off ], ];
Examples:
// Treat column changes as errors, and stop reporting data updates 'rules' => [ 'change-column' => 'error', 'data-mutation' => false, ], // Strict production setup: never trust a migration the checker could not read 'rules' => [ 'analysis-failed' => 'error', ], // Guard staging as well as production 'guard' => [ 'enabled' => env('SAFE_MIGRATIONS_GUARD', false), 'environments' => ['production', 'staging'], // ... ],
| Environment variable | Default | Effect |
|---|---|---|
SAFE_MIGRATIONS_GUARD |
false |
Turn the migrate guard on |
SAFE_MIGRATIONS_STRICT |
false |
Guard blocks on warnings too |
SAFE_MIGRATIONS_ALLOW_UNSAFE |
false |
Switch the guard off temporarily |
These are read through the config, so after changing them on a server with cached config, run php artisan config:cache again.
Command reference
php artisan safe-migrations:check
Reports unsafe operations in pending migrations. Never changes the database.
| Option | Description |
|---|---|
--database=NAME |
Database connection to check against. Its driver decides which rules apply. Default: your default connection |
--path=PATH |
Check migrations in this path instead of the default ones (can be repeated) |
--realpath |
--path values are absolute paths |
--all |
Check every migration, including ones that already ran |
--strict |
Exit with 1 on warnings too |
--format=json |
Print JSON instead of the readable report |
Exit codes: 0 = safe, 1 = unsafe (errors, or warnings with --strict).
Examples:
# Check against a specific connection php artisan safe-migrations:check --database=pgsql # Check one module's migrations php artisan safe-migrations:check --path=modules/Billing/database/migrations # Fail on warnings as well php artisan safe-migrations:check --strict
php artisan migrate:safe
Runs the check, then migrate if it passes.
| Option | Description |
|---|---|
--database, --path, --realpath, --force, --step, --seed |
Passed on to migrate |
--strict |
Refuse to migrate on warnings too |
--unsafe |
Migrate even if unsafe operations are found |
JSON output
php artisan safe-migrations:check --format=json prints:
{
"migrations": [
"2024_02_01_000000_drop_legacy_from_users"
],
"errors": 1,
"warnings": 0,
"findings": [
{
"migration": "2024_02_01_000000_drop_legacy_from_users",
"rule": "drop-column",
"severity": "error",
"subject": "users.legacy",
"message": "Dropping column [users.legacy] destroys its data, and app servers still running the old code will fail on queries that use it.",
"suggestion": "Remove every use of the column from the code and deploy that first, then drop the column in a follow-up migration.",
"sql": "alter table \"users\" drop column \"legacy\""
}
],
"suppressed": []
}
migrations: the pending migrations that were checked.findings: problems that count towards the result.suppressed: problems allowed by#[AllowUnsafe], same shape asfindings.
Use it to post a comment on a pull request or feed another tool.
FAQ
Will running the check change my database?
No. Every database connection is in pretend mode during the check, so nothing is created, changed or deleted, not even the migrations table. Migrations that try to bypass this by using PDO directly are blocked and reported. This is covered by tests on real MySQL, MariaDB and PostgreSQL servers.
HTTP requests (Http::), mail, notifications, queued jobs, dispatch(), events, cache, storage, processes (Process::) and Artisan::call() are faked during the check, so they don't happen, and the real services are put back afterwards. Plain PHP in up() that doesn't go through Laravel, such as file_put_contents(), runs for real. See Limitations.
Does it work with raw queries?
Yes. It reads the SQL your migration would run, so DB::statement(), DB::unprepared() (every statement in the string) and query builder calls with DB::raw() are all checked, including SQL with comments in it. Direct PDO calls (DB::getPdo()->exec(...)) are blocked and reported for review. See Raw SQL.
My migration uses more than one database. Is that handled?
Yes. Statements sent through Schema::connection('other') or DB::connection('other') are checked with that connection's database rules, and never executed. A migration with its own protected $connection = 'other'; is checked against that connection, including its DB::statement() calls, just like migrate runs it.
Does it check migrations that already ran?
No, only pending ones, which is what matters for the next deploy. Use --all to check every migration file.
Will it slow down my deploy? Hardly. Nothing is executed, so checking a handful of pending migrations takes well under a second.
Can I use it with my local SQLite but production PostgreSQL?
You can, but some rules only apply to one database engine (for example, index locking on PostgreSQL). For the most useful results, run the check against the same kind of database you use in production, for example with --database=pgsql.
Something is flagged, but I know it's fine. What do I do?
Add #[AllowUnsafe('rule-name', reason: '...')] to that migration. The reason stays next to the code for whoever reviews it. See When a finding is intentional.
Does it check down()?
Yes, since 1.3.0. down() is dry-run on the schema up() leaves behind, and anything it would break on tables or columns that existed before up() is reported as unsafe-rollback. Undoing what up() added is not reported. Turn on missing-down to also report migrations that can't be rolled back at all.
Does it run my migration's PHP, or read it?
Both. The dry run runs up() and down() with the database in pretend mode, and the source check also reads the PHP of up() without running it, to find what a dry run can't show (skipped Schema::hasColumn() branches and code that reads rows).
Limitations
-
Not every side effect is intercepted. The check really runs your migration's
up()anddown()methods. Database statements are recorded instead of executed, and these Laravel services are swapped for fakes while it runs:- HTTP client (
Http::), mail, notifications, queue and job dispatching (dispatch(),Bus::): recorded, nothing is sent - events (
event(),Event::, model events): recorded, listeners don't run - cache (
Cache::,cache()): an in-memory store, so nothing is written to your real cache - storage (
Storage::): a temporary folder that is deleted afterwards. Reads come back empty, so a migration that reads a file from storage may be reported asanalysis-failed - processes (
Process::) andArtisan::call(): recorded, nothing runs
Code that doesn't go through those services still runs, for example
file_put_contents(),exec(),curl, a Guzzle client you create yourself, orRedis::. Keep migrations to database changes, and put the rest in a command or job. - HTTP client (
-
Pretend mode returns no data. During the dry run,
selectqueries return nothing. A migration that doesif (Schema::hasColumn(...))or reads rows to decide what to do is checked along the path it takes when those checks come back empty. The source check reports these cases (schema-condition,reads-data) so you know what to review by hand. If the dry run throws an exception, the migration is reported as ananalysis-failedwarning. -
The source check only reads
up()and follows simple patterns. It seesDB::table('x')->get()andUser::where(...)->get()written directly inup(), not a query stored in a variable first or code in another class the migration calls. -
It can't know your table sizes. Warnings describe what can lock; on a table with 200 rows it doesn't matter. Use your judgement, and
#[AllowUnsafe]once you've checked. -
Direct PDO calls are blocked, not analysed. The check can't see what
DB::getPdo()->exec(...)would do, so it stops the call and reports the migration asanalysis-failed. Anything after that call in the same migration is not checked. PreferDB::statement(), which is checked. -
Rollback analysis checks
down()right afterup(). It sees what a rollback of the pending migrations would break, not a rollback of migrations that already ran. -
MariaDB's behaviour depends on its version. Since 11.2, MariaDB can copy a table while writes go on, so
table-copydescribes both cases andunsupported-algorithmdoesn't checkLOCK=NONEon MariaDB. -
SQL Server is not supported.
-
The guard reads only the first
--pathgiven tomigrate.
Troubleshooting
"Nothing to check: no pending migrations" but I just created one.
The check only looks at migrations that haven't run. If you already ran it locally, roll back (php artisan migrate:rollback) or use --all.
Nothing is flagged in CI, but it should be. The CI database is probably empty, so every table counts as new. Migrate it with your main branch first (see the CI example).
A rule fires for something I know is safe.
Mark that migration with #[AllowUnsafe('rule-name', reason: '...')]. If it's never relevant for your project, turn the rule off in the config.
PostgreSQL or MySQL rules don't fire.
Database-specific rules only apply when the checked connection is that database. Run the check against the same kind of database you use in production (--database=pgsql, --database=mysql), not your local SQLite.
The guard doesn't block migrate.
Check that SAFE_MIGRATIONS_GUARD=true, that APP_ENV is listed in guard.environments, that SAFE_MIGRATIONS_ALLOW_UNSAFE isn't set, and run php artisan config:cache again if config is cached.
Developing this package
Everything runs in Docker, including MySQL 8.4, MariaDB 11.4 and PostgreSQL 17 for the integration tests:
docker compose build docker compose run --rm tests docker compose run --rm tests composer analyse docker compose down
tests/Unitchecks the rules against hand-written SQL.tests/Feature/GrammarIntegrationTest.phpruns real Laravel schema code through each database's grammar, so the rules are tested against the exact SQL Laravel generates on SQLite, MySQL and PostgreSQL.tests/Feature/CommandsTest.phpcovers the commands,#[AllowUnsafe]and the guard.tests/Feature/SideEffectsTest.phpchecks that HTTP calls, mail, notifications and jobs inup()don't happen during the check, and that the real services are restored.tests/Feature/RollbackAndIsolationTest.phpcovers rollback analysis (unsafe-rollback,missing-down) and checks that storage, cache, events, processes andArtisan::call()are faked and restored.tests/Unit/SourceAnalyzerTest.phpchecks the source rules (schema-condition,reads-data) against migration code.tests/Feature/TransactionDetectionTest.phpchecks that statements know whether they run inside the migration's transaction, decided the same way asmigrate.tests/Feature/MySqlOnlineDdlTest.phpruns every statementunsupported-algorithmcalls "rejected" on real MySQL and MariaDB servers, and checks that the server really rejects it and that the in-place alternatives really work.tests/Feature/RealDatabaseCommandsTest.phpruns the commands end to end on real MySQL, MariaDB and PostgreSQL, including rollback analysis,lock-timeoutand MariaDB'sWAIT/SET STATEMENT.composer analyseruns Larastan (PHPStan for Laravel) at level 8.
Without Docker, composer install && vendor/bin/phpunit runs the SQLite tests and skips MySQL, MariaDB and PostgreSQL.
To add a rule: implement HamzaWakrim\SafeMigrations\Rules\Rule, add it to Analyzer::defaultRules(), add its id to config/safe-migrations.php, and add cases to both test files.
Contributing
Bug reports, ideas for new rules and pull requests are welcome on GitHub.
When reporting a false positive or a missed problem, please include the migration code and your database (MySQL, PostgreSQL or SQLite, and its version). For pull requests, run docker compose run --rm tests and docker compose run --rm tests composer analyse first.
License
MIT. See LICENSE.