PHPackages                             samody/laravel-migration-preflight - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. samody/laravel-migration-preflight

ActiveLibrary[Database &amp; ORM](/categories/database)

samody/laravel-migration-preflight
==================================

Pre-migration validation tool for Laravel migrations

v1.10.1(1mo ago)1163↓40%MITPHPPHP ^8.2 || ^8.3CI passing

Since Apr 13Pushed 1mo agoCompare

[ Source](https://github.com/samody2006/laravel-migration-preflight)[ Packagist](https://packagist.org/packages/samody/laravel-migration-preflight)[ Docs](https://github.com/samody/laravel-migration-preflight)[ RSS](/packages/samody-laravel-migration-preflight/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (2)Versions (10)Used By (0)

Laravel Migration Preflight
===========================

[](#laravel-migration-preflight)

A Laravel package that validates migrations before execution to prevent schema-related failures. Catch migration errors early before they partially execute and corrupt your database.

Why Use This?
-------------

[](#why-use-this)

The common problem with Laravel migrations:

- **Migration fails mid-way** → Database is half-migrated
- **Foreign keys reference non-existent tables** → Migration crashes
- **Indexes created on missing columns** → Partial table state
- **No visibility into what will break** → Costly database rollbacks

**Migration Preflight prevents all of this** by validating your migrations before execution.

Installation
------------

[](#installation)

```
composer require samody/laravel-migration-preflight
```

Quick Start
-----------

[](#quick-start)

```
# Validate all pending migrations
php artisan migrate:preflight

# Get detailed error info with code context
php artisan migrate:preflight --verbose
```

Features
--------

[](#features)

### Core Validation (Original)

[](#core-validation-original)

- ✅ **Foreign Key Validation**: Detect missing referenced tables for `foreignId()->constrained()` and `foreign()->references()->on()`
- ✅ **Table Existence Checks**: Ensure tables exist when using `Schema::table()`
- ✅ **Column Existence Checks**: Verify columns exist when using `after()`, `dropColumn()`, `renameColumn()`, `change()`
- ✅ **Smart Pluralization**: Correctly guesses referenced table names using Laravel's `Str::plural()`
- ✅ **Zero-Migration Safety**: Handles fresh databases and empty migration folders without errors

### Phase 1 Enhancements

[](#phase-1-enhancements)

- ✨ **Index Constraint Validation**: Detect indexes created on non-existent columns
- ✨ **Unique Constraint Validation**: Validate unique constraints reference existing columns
- ✨ **Full-Text Index Validation**: Check fullText() constraints before migration
- ✨ **Spatial Index Validation**: Validate spatialIndex() constraints
- ✨ **Line Number Tracking**: Know exactly where in your migration file the issue is
- ✨ **Verbose Mode** (`--verbose`): See code context around each error
- ✨ **Better Error Categorization**: Errors typed as `foreign_key`, `missing_table`, `index_constraint`, etc.

### Phase 2 Refinement (NEW)

[](#phase-2-refinement-new)

- 🚀 **Block-Based Validation**: Scopes validation to individual `Schema` closures for high-precision checks
- 🎯 **Up-Method Focus**: Focuses exclusively on the `up()` method to prevent false positives in `down()` methods
- 🧱 **In-Block Creation Awareness**: Tracks columns created in the same block to avoid false errors in `after()`
- 📦 **Multi-Column Support**: Validates array-based operations like `$table->dropColumn(['col1', 'col2'])`
- 🏷️ **Closure Variable Agnosticism**: Detects and uses any closure variable name (e.g., `$table`, `$t`, `$blueprint`)
- 🔍 **Robust Table Detection**: Advanced detection handles multi-line calls and complex formatting variations

Usage
-----

[](#usage)

### Basic Check

[](#basic-check)

```
php artisan migrate:preflight
```

**Output:**

```
Running migration preflight...
Checking: 2024_01_15_123456_create_orders_table
Checking: 2024_01_15_123457_add_indexes_to_orders

Checked: 2 migrations
✓ All migrations passed preflight checks.

```

### Verbose Mode with Context

[](#verbose-mode-with-context)

```
php artisan migrate:preflight --verbose
```

**Output with code context:**

```
Running migration preflight...
Verbose mode enabled

Checking: 2024_01_15_123456_create_orders_table

Preflight FAILED:

2024_01_15_123456_create_orders_table
 - [Line 18] Missing referenced table 'customers' for 'customer_id'
   ─────────────────────────────
   15: $table->decimal('amount', 10, 2);
   16: $table->timestamps();
   17:
   > 18: $table->foreignId('customer_id')->constrained();
   19: });
   ─────────────────────────────

Total errors found: 1

```

Configuration
-------------

[](#configuration)

Publish the config file:

```
php artisan vendor:publish --tag=preflight-config
```

**config/preflight.php:**

```
return [
    'strict' => true,

    'checks' => [
        'missing_tables' => true,         // Check for missing tables
        'missing_columns' => true,        // Check for missing columns
        'foreign_keys' => true,           // Check foreign key references
        'index_constraints' => true,      // Check index constraints
        'unique_constraints' => true,     // Check unique constraints
    ],
];
```

What Gets Validated
-------------------

[](#what-gets-validated)

### Supported Patterns

[](#supported-patterns)

#### Foreign Keys ✅

[](#foreign-keys-)

```
// Automatically pluralizes table name
$table->foreignId('user_id')->constrained();  // Looks for 'users' table

// Explicit table name
$table->foreignId('owner_id')->constrained('users');

// Manual foreign key
$table->foreign('customer_id')->references('id')->on('customers');
```

#### Constraints &amp; Indexes ✅

[](#constraints--indexes-)

```
// Single column index
$table->index('email');

// Unique constraint
$table->unique('email');

// Multi-column unique
$table->unique(['email', 'username']);

// Full-text index
$table->fullText(['title', 'description']);

// Spatial index (MySQL)
$table->spatialIndex('coordinates');
```

#### Column Operations ✅

[](#column-operations-)

```
$table->string('email')->after('name');              // Column must exist
$table->dropColumn('old_field');                     // Column must exist
$table->renameColumn('old_name', 'new_name');        // Column must exist
$table->string('email')->change();                   // Column must exist
```

#### Table Modifications ✅

[](#table-modifications-)

```
Schema::table('users', function ($table) {           // Table must exist
    $table->string('new_field')->default('N/A');
});
```

Example Output
--------------

[](#example-output)

### Scenario: Multiple Errors

[](#scenario-multiple-errors)

```
Preflight FAILED:

2024_01_15_create_orders_table
 - [Line 12] Table 'customers' does not exist
 - [Line 15] Column 'user_id' does not exist on table 'orders' (used in unique())
 - [Line 18] Missing referenced table 'companies' for 'company_id'

2024_01_15_add_indexes
 - [Line 8] Column 'email' does not exist on table 'users' (used in index())

Total errors found: 4

```

Exit Codes
----------

[](#exit-codes)

- 0: Success - All migrations passed preflight checks
- **1**: Failure - Validation errors found

CI/CD Integration
-----------------

[](#cicd-integration)

```
#!/bin/bash
php artisan migrate:preflight
if [ $? -ne 0 ]; then
    echo "❌ Migration validation failed!"
    exit 1
fi
echo "✅ All migrations validated successfully"
```

Testing
-------

[](#testing)

```
vendor/bin/phpunit tests/ --no-coverage
```

**Test Coverage:**

- 30 tests covering all validation scenarios
- Unit tests for constraint parsing
- Feature tests for end-to-end validation
- Reproduction tests for reported issues

Limitations &amp; Future Enhancements
-------------------------------------

[](#limitations--future-enhancements)

### Current Limitations

[](#current-limitations)

- Does not validate data type compatibility between foreign keys
- Does not detect circular foreign key dependencies
- Does not validate cascading delete implications
- Does not check database-specific constraints

### Roadmap

[](#roadmap)

- Phase 2: JSON/CSV export formats
- Phase 3: Data type compatibility checks
- Phase 4: Migration dependency detection
- Phase 5: CI/CD GitHub Actions integration

Real-World Benefits
-------------------

[](#real-world-benefits)

### Development

[](#development)

✅ Catch migration errors before they cause issues ✅ Know exact line number of the problem ✅ See code context immediately ✅ Iterate faster without database rollbacks

### Staging/Production

[](#stagingproduction)

✅ Validate migrations before production deployments ✅ Prevent partial database state corruption ✅ CI/CD pipeline integration ✅ Zero downtime verification

### Team Collaboration

[](#team-collaboration)

✅ Code reviewers can run preflight checks ✅ Catch common mistakes in PRs ✅ Standardize migration best practices ✅ Reduce back-and-forth on deployment issues

License
-------

[](#license)

MIT - See LICENSE.md for details

Support
-------

[](#support)

- 🐛 Issues: [GitHub Issues](https://github.com/samody/laravel-migration-preflight/issues)
- 📧 Email:
- ⭐ Please star if this package helps you!

---

**Made with ❤️ to prevent database nightmares**

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance94

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~3 days

Total

9

Last Release

30d ago

PHP version history (2 changes)v1.0.0PHP &gt;=8.1

v1.0.4PHP ^8.2 || ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/489e6539d16030e5266af9ef15a0e11e34fd71db2c038af482ebc6d46d070af5?d=identicon)[samody2006](/maintainers/samody2006)

---

Top Contributors

[![samody2006](https://avatars.githubusercontent.com/u/9530145?v=4)](https://github.com/samody2006 "samody2006 (18 commits)")

---

Tags

laraveldatabasetoolmigrationspreflight

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/samody-laravel-migration-preflight/health.svg)

```
[![Health](https://phpackages.com/badges/samody-laravel-migration-preflight/health.svg)](https://phpackages.com/packages/samody-laravel-migration-preflight)
```

###  Alternatives

[nwidart/db-exporter

Export your database quickly and easily as a Laravel Migration and all the data as a Seeder class.

37839.1k](/packages/nwidart-db-exporter)[nunomaduro/laravel-optimize-database

Publishes migrations that make your database production ready.

26241.3k](/packages/nunomaduro-laravel-optimize-database)[awssat/laravel-sync-migration

Laravel tool helps to sync migrations without refreshing the database

10923.3k](/packages/awssat-laravel-sync-migration)[orptech/laravel-migration-partition

Laravel extensions that extends Illuminate to enable partitioned table creation within Laravel migrations.

3628.3k](/packages/orptech-laravel-migration-partition)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
