New

Just launched: Vueblocks, a brand-new search engine for Vue packages! Explore Vueblocks →

grazulex/laravel-strongmigrations

Detect dangerous migrations before they break production. Catch unsafe operations, get guided alternatives, and keep your database safe.
3,628 1
Install
composer require grazulex/laravel-strongmigrations
Latest Version:v1.4.0
PHP:^8.4
Laravel:12 · 13
Older releases:11
License:MIT
Last Updated:Nov 9, 2026
Links: GitHub  ·  Packagist
Maintainer: Grazulex

Laravel Strong Migrations

[!TIP] What Laravel Strong Migrations does for you — Catch the migration that would lock your users table for ten minutes before it reaches production. Static analysis of your migrations with database-specific rules, in block or warn mode, ready for CI.

This package is free and maintained on my own time. If it saves you hours, a small contribution helps me keep it going: 💖 GitHub Sponsors · ☕ Buy Me a Coffee · PayPal

Tests Code Quality Latest Version on Packagist PHP Version License

Detect dangerous migrations before they hit production. Inspired by the Rails strong_migrations gem.

Laravel Strong Migrations analyzes your migration files using AST parsing (nikic/php-parser) and warns you about operations that could cause downtime, data loss, or lock contention on large tables.

Features

  • 16+ built-in rules covering common dangerous operations
  • Database-aware — version-specific rules for MySQL, MariaDB, and PostgreSQL
  • Two modes — block (prevents migration) or warn (displays warning)
  • AST-based analysis — no migration execution required
  • CI/CD ready — JSON and GitHub Actions output formats
  • Customizable — disable rules, add custom checks, bypass with safetyAssured
  • Multilingual — English and French translations included

Installation

composer require grazulex/laravel-strongmigrations

Publish the configuration:

php artisan strong-migrations:install

How It Works

Strong Migrations listens to Laravel's MigrationStarted event. When you run php artisan migrate, each migration is parsed and checked against the rule engine before it executes.

If a dangerous operation is detected:

  • In block mode (default): an exception is thrown with a safe alternative
  • In warn mode: a warning is displayed, migration proceeds

Rules

Common Rules (All Databases)

Rule ID Detects Severity
remove_column Dropping a column High
rename_column Renaming a column High
rename_table Renaming a table High
create_table_force dropIfExists before create High
backfill_in_migration Data + schema changes in same migration Medium
add_auto_increment Adding auto-increment columns Medium
raw_sql Raw SQL statements Warning
wide_index Index with > 3 columns Low

MySQL / MariaDB Rules

Rule ID Detects Severity
add_column_with_default Adding NOT NULL column with default (< MySQL 8.0.12 / MariaDB 10.3.2) High
change_column_type Changing column type (table rewrite) High
set_not_null_mysql Setting NOT NULL constraint Medium

PostgreSQL Rules

Rule ID Detects Severity
add_index_non_concurrent Adding index without CONCURRENTLY High
add_foreign_key Adding foreign key (locks both tables) High
add_check_constraint Adding check constraint Medium
add_unique_constraint Adding unique constraint Medium
json_column Using json instead of jsonb Low
set_not_null_pgsql Setting NOT NULL (full table scan) Medium

add_index_non_concurrent, add_unique_constraint and add_foreign_key only report changes to existing tables. Indexes, unique constraints and foreign keys declared inside Schema::create() (including Schema::connection(...)->create()) are not reported: the table is new and empty, so CONCURRENTLY or NOT VALID brings nothing there.

Foreign Keys and Index Removals

Foreign keys are detected both with $table->foreign('user_id')->references('id')->on('users') and with the foreignId() shorthand. foreignId(), foreignIdFor(), foreignUuid() and foreignUlid() create a foreign key (an add_foreign_key operation) when chained with ->constrained() or ->references()->on(). A plain $table->foreignId('user_id') with neither only adds a column, so it is not reported as a foreign key.

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained();               // add_foreign_key on user_id
    $table->foreignId('author_id')->constrained('users');      // add_foreign_key, referenced table "users"
    $table->foreignIdFor(Team::class, 'team_id')->constrained(); // add_foreign_key on team_id
});

The analyzer also emits removal operations that custom checks can consume (see Custom Checks):

Blueprint method Operation type(s)
dropForeign(), dropForeignIdFor() OperationType::RemoveForeignKey
dropConstrainedForeignId(), dropConstrainedForeignIdFor() OperationType::RemoveForeignKey + OperationType::RemoveColumn
dropIndex(), dropUnique(), dropPrimary(), dropFullText(), dropSpatialIndex() OperationType::RemoveIndex

RemoveIndex operations carry index_type (index, unique, primary, fulltext or spatial), index_name and columns in their details; RemoveForeignKey operations carry foreign_key_name and columns. When a column list is given (for example dropForeign(['user_id'])), the first column is also set as the operation column. Because dropConstrainedForeignId() drops the column too, it is reported by the remove_column rule.

Usage

Automatic Protection

Once installed, Strong Migrations automatically checks all migrations during php artisan migrate:

$ php artisan migrate

Dangerous operation detected in migration: 2025_01_15_000001_drop_email.php

[remove_column] Removing column `email` that is used by the application
will cause errors until application servers are restarted.

Safe alternative:

Step 1 - Ignore the column in your Eloquent model:
    protected static array $ignoredColumns = ['email'];

Step 2 - Deploy the code.

Step 3 - Create a migration that drops the column, wrapped in:
    StrongMigrations::safetyAssured(function () { ... });

Artisan Commands

Check all migrations
# Text output (default)
php artisan migrate:check

# JSON output (for CI/CD)
php artisan migrate:check --format=json

# GitHub Actions annotations
php artisan migrate:check --format=github

# Custom path
php artisan migrate:check --path=database/migrations

migrate:check honours the start_after baseline: migration files whose timestamp is lower than or equal to start_after are skipped, exactly like the migration listener does.

Analyze a specific migration
php artisan migrate:analyze 2025_01_15_000001_drop_email.php

Bypassing Checks

When you've verified a migration is safe, wrap it in safetyAssured:

use Grazulex\StrongMigrations\StrongMigrations;

return new class extends Migration
{
    public function up(): void
    {
        StrongMigrations::safetyAssured(function () {
            Schema::table('users', function (Blueprint $table) {
                $table->dropColumn('legacy_field');
            });
        });
    }
};

Custom Checks

Add custom rules in a service provider:

use Grazulex\StrongMigrations\StrongMigrations;

StrongMigrations::addCheck(function (Operation $operation, DatabaseContext $context) {
    if ($operation->type === OperationType::AddColumn && $operation->column === 'metadata') {
        StrongMigrations::stop('Use `data` instead of `metadata` for consistency.');
    }
});

Custom Messages

Override the default message for the next violation:

StrongMigrations::setMessage('This migration has been reviewed and approved by the DBA team.');

Configuration

// config/strong-migrations.php
return [
    // Enable/disable the package
    'enabled' => env('STRONG_MIGRATIONS_ENABLED', true),

    // 'block' or 'warn'
    'mode' => env('STRONG_MIGRATIONS_MODE', 'block'),

    // Override auto-detected database driver
    'database_driver' => env('STRONG_MIGRATIONS_DRIVER'),

    // Override auto-detected database version
    'database_version' => env('STRONG_MIGRATIONS_VERSION'),

    // Skip migrations up to this timestamp, inclusive (format: YYYY_MM_DD_HHMMSS).
    // Applies to both `php artisan migrate` and `php artisan migrate:check`.
    'start_after' => null,

    // Disable specific rules by ID
    'disabled_checks' => [
        // 'remove_column',
        // 'raw_sql',
    ],

    // Session timeouts applied while each migration runs (null = untouched)
    'timeouts' => [
        'statement_timeout' => '1h',   // PostgreSQL
        'lock_timeout' => '10s',        // PostgreSQL
        'lock_wait_timeout' => 10,      // MySQL / MariaDB (seconds)
    ],
];

Timeouts

When a migration starts, the configured timeouts are set on the migration's connection, so a migration waiting on a busy table fails fast instead of queueing every other query behind it. When the migration ends, the previous session values are restored.

Driver Settings Query
PostgreSQL statement_timeout, lock_timeout set_config(...) (same as SET)
MySQL / MariaDB lock_wait_timeout SET SESSION lock_wait_timeout = ...
SQLite / others — nothing is executed

PostgreSQL values accept an integer (milliseconds) or a string with a unit ('10s', '1h'). The MySQL value is a whole number of seconds. Set any key to null to leave that setting untouched. Timeouts are applied regardless of safetyAssured and start_after, and are not applied when the package is disabled (enabled => false).

CI/CD Integration

GitHub Actions

- name: Check migrations
  run: php artisan migrate:check --format=github

This outputs annotations that appear directly on pull request diffs.

Generic CI

- name: Check migrations
  run: php artisan migrate:check --format=json

Returns exit code 1 if any violations are found.

Supported Databases

Database Version Notes
MySQL 5.7+ Version-aware rules (8.0.12+ allows instant ADD COLUMN)
MariaDB 10.2+ Version-aware rules (10.3.2+ allows instant ADD COLUMN)
PostgreSQL 12+ CONCURRENTLY, foreign key, and constraint rules
SQLite Any Reduced rule set (safe for development)

Requirements

  • PHP 8.4+
  • Laravel 12.x or 13.x

Testing

composer test

Code Quality

composer phpstan    # PHPStan level 8
composer pint       # Laravel Pint

Contributing

Please see CONTRIBUTING.md for details.

Security

If you discover a security vulnerability, please see SECURITY.md.

Support This Package

Laravel Strong Migrations is free, open source and maintained on my own time. If it saves you hours, here is how you can give back:

License

The MIT License (MIT). Please see LICENSE.md for more information.

Related Packages

mahbubhelal/refresh-databases

A Laravel package that extends RefreshDatabase trait to support multiple databas...

100 0
nunomaduro/laravel-optimize-database

Publishes migrations that make your database production ready.

67,581 267
proai/laravel-super-migrations

This Laravel package is useful for big databases for a better migrations structu...

2,826 11
maxim-oleinik/blade-migrations

Raw SQL database migration tool for PHP apps

2,350 0

Version History

Version Released PHP Laravel License
v1.4.0 ^8.4 ^12.0|^13.0 MIT
v1.3.2 ^8.4 ^12.0|^13.0 MIT
v1.3.1 ^8.4 ^12.0|^13.0 MIT
v1.3.0 ^8.4 ^12.0|^13.0 MIT
v1.2.1 ^8.4 ^12.0|^13.0 MIT