PHPackages                             zitansmail/migration-orderer - 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. zitansmail/migration-orderer

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

zitansmail/migration-orderer
============================

Automatically order Laravel migrations based on foreign key dependencies to prevent constraint errors

v1.0.0(7mo ago)011MITPHPPHP ^8.1

Since Sep 28Pushed 7mo agoCompare

[ Source](https://github.com/zitansmail/laravel-migration-orderer)[ Packagist](https://packagist.org/packages/zitansmail/migration-orderer)[ Docs](https://github.com/zitansmail/laravel-migration-orderer)[ RSS](/packages/zitansmail-migration-orderer/feed)WikiDiscussions main Synced 1mo ago

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

📦 MigrationOrderer — Dependency-Aware Laravel Migration Ordering
================================================================

[](#-migrationorderer--dependency-aware-laravel-migration-ordering)

[![Laravel Package](https://camo.githubusercontent.com/9eb4bcd95946d1e5fc02a82cfe1d9d1b338af608fb83f72b47509432d5cfe4ec/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d5061636b6167652d4646324432303f6c6f676f3d6c61726176656c)](https://laravel.com)[![Tests](https://camo.githubusercontent.com/214930dd574621ac62e96dbd4d3060592e9a26c296be4fb76e2fc63fe85546ef/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f54657374732d50617373696e672d627269676874677265656e)](https://github.com/zitansmail/migration-orderer)[![PHP Version](https://camo.githubusercontent.com/83dd395020c37276225039739320f6c8e7e99963ab21ee3d09282cb48dad2a60/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d626c7565)](https://php.net)

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 --dev
```

---

🎯 The Problem
-------------

[](#-the-problem)

Ever 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.

💡 The Solution
--------------

[](#-the-solution)

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

---

🚀 Features
----------

[](#-features)

- 🔍 **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

---

✅ Requirements
--------------

[](#-requirements)

- PHP 8.1+
- Laravel 10.x / 11.x / 12.x

---

📦 Installation
--------------

[](#-installation)

```
composer require zitansmail/migration-orderer --dev
```

That's it! The package auto-registers and creates its tracking table automatically when needed. No manual migrations required.

---

🛠 Usage
-------

[](#-usage)

### 1. Preview Dependencies (Safe, No Changes)

[](#1-preview-dependencies-safe-no-changes)

```
php artisan migrate:ordered --preview
```

**Example 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.

```

### 2. Reorder Files

[](#2-reorder-files)

```
php artisan migrate:ordered --reorder
```

**With confirmation bypass (CI/automation):**

```
php artisan migrate:ordered --reorder --force
```

### 3. Undo Last Reorder

[](#3-undo-last-reorder)

```
php artisan migrate:ordered --undo-last
```

### 4. Custom Migration Paths

[](#4-custom-migration-paths)

```
php artisan migrate:ordered --preview --path=modules/Blog/database/migrations
```

---

🔍 Supported Foreign Key Patterns
--------------------------------

[](#-supported-foreign-key-patterns)

The 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');
```

---

🔄 Workflow Examples
-------------------

[](#-workflow-examples)

### Basic Workflow

[](#basic-workflow)

```
# 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
```

### Team Development

[](#team-development)

```
# 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"
```

---

🚨 Error Handling
----------------

[](#-error-handling)

### Circular Dependencies

[](#circular-dependencies)

```
Migration Orderer Error: Circular dependency detected:
create_users_table.php -> create_roles_table.php -> create_users_table.php
```

**Solution:** Break the cycle by:

- Moving foreign keys to separate migrations
- Using nullable foreign keys initially
- Deferring constraints with `Schema::enableForeignKeyConstraints()`

### Missing Dependencies

[](#missing-dependencies)

The preview shows missing tables that your migrations reference but don't create:

```
Missing: ["external_api_users", "legacy_data"]

```

---

🧭 Command Reference
-------------------

[](#-command-reference)

```
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
```

---

🔒 Safety Features
-----------------

[](#-safety-features)

- **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

---

🛡️ Best Practices
-----------------

[](#️-best-practices)

### Development Workflow

[](#development-workflow)

1. **Always preview first** to understand dependencies
2. **Commit before reordering** for easy rollback
3. **Use feature branches** for complex schema changes
4. **Test migrations** in staging before production

### Schema Design

[](#schema-design)

- 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

### Team Collaboration

[](#team-collaboration)

- Run `--preview` before pushing migration changes
- Include reordering in your CI/CD pipeline
- Document complex dependency relationships
- Use consistent naming conventions

---

🧪 Testing
---------

[](#-testing)

The package includes focused tests covering core functionality:

```
# Run the test suite
composer test

# With coverage
composer test-coverage
```

Essential 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

---

🤝 Contributing
--------------

[](#-contributing)

We welcome contributions! Here's how you can help improve MigrationOrderer:

### Quick Start

[](#quick-start)

```
git clone https://github.com/zitansmail/migration-orderer
cd migration-orderer
composer install
composer test
```

### Contributing Guidelines

[](#contributing-guidelines)

**🐛 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**

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/your-feature`
3. Write tests for new functionality
4. Ensure all tests pass: `composer test`
5. Follow PSR-12 coding standards
6. Submit a pull request with clear description

**📝 Documentation**

- Fix typos and improve clarity
- Add examples for complex features
- Update README when adding new functionality

### Development Guidelines

[](#development-guidelines)

- Write tests for all new features
- Keep backwards compatibility
- Follow existing code patterns
- Add meaningful commit messages

---

📝 License
---------

[](#-license)

MIT License. See [LICENSE](https://github.com/ludoguenet/zap-for-laravel/blob/main/LICENSE) for details.

---

📚 Learn More
------------

[](#-learn-more)

**📖 Technical Deep Dive**Read the complete story behind MigrationOrderer's development: [Solving Laravel Migration Dependency Hell: Building MigrationOrderer Package](https://www.blog.zitansmail.com/blogs/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

---

🙏 Credits
---------

[](#-credits)

Created by [Zitane Smail](https://github.com/zitansmail)

Built with ❤️ for the Laravel community.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance62

Regular maintenance activity

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

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

Unknown

Total

1

Last Release

232d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/af1abe09790a5c0c0e6b327c4d99775227d2017da9e873ad422bb1069f8669f9?d=identicon)[zitansmail](/maintainers/zitansmail)

---

Top Contributors

[![zitansmail](https://avatars.githubusercontent.com/u/52583047?v=4)](https://github.com/zitansmail "zitansmail (1 commits)")

---

Tags

laraveldatabasemigrationstopological sortdependenciesforeign-keys

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/zitansmail-migration-orderer/health.svg)

```
[![Health](https://phpackages.com/badges/zitansmail-migration-orderer/health.svg)](https://phpackages.com/packages/zitansmail-migration-orderer)
```

###  Alternatives

[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[cybercog/laravel-clickhouse

ClickHouse migrations for Laravel

163166.8k](/packages/cybercog-laravel-clickhouse)[toponepercent/baum

Baum is an implementation of the Nested Set pattern for Eloquent models.

3154.7k](/packages/toponepercent-baum)[dragon-code/laravel-data-dumper

Adding data from certain tables when executing the `php artisan schema:dump` console command

3418.6k](/packages/dragon-code-laravel-data-dumper)[orptech/laravel-migration-partition

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

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

PHPackages © 2026

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