Automatically analyze and reorder Laravel migrations based on foreign key dependencies. Prevent foreign key constraint errors by ensuring tables are created in the correct order.
composer require zitansmail/migration-orderer --devEver encountered this error when running migrations?
SQLSTATE[HY000]: General error: 1005 Can't create table `posts`
(errno: 150 "Foreign key constraint is incorrectly formed")This happens when migrations create foreign keys to tables that don't exist yet. Traditional solutions require manually renaming migration files or creating migrations in perfect chronological order.
MigrationOrderer automatically:
- Scans your migrations for foreign key dependencies
- Builds a dependency graph using topological sorting
- Reorders files to ensure dependencies come first
- Shows you exactly what needs to be fixed
- π Smart Detection: Finds
foreignId(),constrained(),foreignIdFor(), and legacy foreign keys - π§© Topological Sort: Uses graph algorithms to compute safe execution order
- ποΈ Rich Preview: Shows current vs computed positions with dependency details
- π‘οΈ Circular Detection: Identifies and reports circular dependencies with clear error messages
- π Safe Reordering: Renames files while maintaining full undo capability
- πΎ State Management: Tracks changes in database for reliable undo operations
- π Flexible Paths: Works with custom migration directories and modular setups
- β Production Ready: Comprehensive test coverage and error handling
- PHP 8.1+
- Laravel 10.x / 11.x / 12.x
composer require zitansmail/migration-orderer --devThat's it! The package auto-registers and creates its tracking table automatically when needed. No manual migrations required.
php artisan migrate:ordered --previewExample Output:
+-------------+----------------------+-------------+---------------+------------------+------------------------+
| # (Computed)| Migration | Current Pos | Status | Dependencies | Issue |
+-------------+----------------------+-------------+---------------+------------------+------------------------+
| 1 | create_users_table | 2 | NEEDS REORDER | - | - |
| 2 | create_posts_table | 1 | NEEDS REORDER | create_users_... | Depends on: create_... |
+-------------+----------------------+-------------+---------------+------------------+------------------------+
β οΈ 1 migration(s) need reordering for dependency safety.
php artisan migrate:ordered --reorderWith confirmation bypass (CI/automation):
php artisan migrate:ordered --reorder --forcephp artisan migrate:ordered --undo-lastphp artisan migrate:ordered --preview --path=modules/Blog/database/migrationsThe scanner detects all modern Laravel foreign key patterns:
// β
Modern foreignId with implicit constraint
$table->foreignId('user_id')->constrained();
// β
Modern foreignId with explicit table
$table->foreignId('author_id')->constrained('users');
// β
ForeignIdFor helper
$table->foreignIdFor(User::class);
$table->foreignIdFor(User::class, 'author_id');
// β
Legacy foreign key syntax
$table->foreign('user_id')->references('id')->on('users');
// β
Legacy unsigned big integer (partial detection)
$table->unsignedBigInteger('user_id');
// β οΈ Polymorphic relationships (detected but no dependency)
$table->morphs('commentable');
$table->uuidMorphs('taggable');# 1. Check current state
php artisan migrate:ordered --preview
# 2. Fix ordering if needed
php artisan migrate:ordered --reorder
# 3. Run migrations normally
php artisan migrate
# 4. Undo if something goes wrong
php artisan migrate:ordered --undo-last# Before merging a feature branch
git checkout feature/user-system
php artisan migrate:ordered --preview
php artisan migrate:ordered --reorder --force
git add database/migrations/
git commit -m "Fix migration dependency order"Migration Orderer Error: Circular dependency detected:
create_users_table.php -> create_roles_table.php -> create_users_table.phpSolution: Break the cycle by:
- Moving foreign keys to separate migrations
- Using nullable foreign keys initially
- Deferring constraints with
Schema::enableForeignKeyConstraints()
The preview shows missing tables that your migrations reference but don't create:
Missing: ["external_api_users", "legacy_data"]
php artisan migrate:ordered [options]
Options:
--preview Show dependency analysis without making changes
--reorder Rename files to match computed order
--undo-last Restore files from last reorder operation
--path=PATH Custom migrations directory
--force Skip confirmation prompts- Preview First: Always shows what will change before making modifications
- Atomic Operations: File renames are tracked; failures can be undone
- State Persistence: Every reorder is logged in the database
- Backup Strategy: Undo capability restores exact previous state
- Non-Destructive: Default mode makes no changes to your files
- Validation: Detects and prevents circular dependencies
- Always preview first to understand dependencies
- Commit before reordering for easy rollback
- Use feature branches for complex schema changes
- Test migrations in staging before production
- Avoid circular foreign key dependencies
- Consider nullable foreign keys for complex relationships
- Use pivot tables for many-to-many relationships
- Plan table creation order during initial design
- Run
--previewbefore pushing migration changes - Include reordering in your CI/CD pipeline
- Document complex dependency relationships
- Use consistent naming conventions
The package includes focused tests covering core functionality:
# Run the test suite
composer test
# With coverage
composer test-coverageEssential test coverage:
- β Command Interface - Preview, reorder, undo operations
- β Dependency Detection - All foreign key patterns and missing dependencies
- β Circular Dependencies - Detection and error handling
- β File Operations - Safe reordering with automatic table creation
We welcome contributions! Here's how you can help improve MigrationOrderer:
git clone https://github.com/zitansmail/migration-orderer
cd migration-orderer
composer install
composer testπ Reporting Bugs
- Check existing issues before creating new ones
- Include Laravel version, PHP version, and error details
- Provide minimal reproduction steps
β¨ Suggesting Features
- Open an issue with a clear description
- Explain the use case and expected behavior
- Include code examples if applicable
π§ Code Contributions
- Fork the repository
- Create a feature branch:
git checkout -b feature/your-feature - Write tests for new functionality
- Ensure all tests pass:
composer test - Follow PSR-12 coding standards
- Submit a pull request with clear description
π Documentation
- Fix typos and improve clarity
- Add examples for complex features
- Update README when adding new functionality
- Write tests for all new features
- Keep backwards compatibility
- Follow existing code patterns
- Add meaningful commit messages
MIT License. See LICENSE for details.
π Technical Deep Dive Read the complete story behind MigrationOrderer's development: Solving Laravel Migration Dependency Hell: Building MigrationOrderer Package
The blog post covers:
- The problem and motivation behind the package
- Technical implementation details and algorithms
- Real-world usage patterns and team workflows
- Development challenges and lessons learned
- Future enhancements and roadmap
Created by Zitane Smail
Built with β€οΈ for the Laravel community.