Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Schema Builder Laravel Package

cycle/schema-builder

Cycle ORM Schema Builder lets you define and configure your ORM and database schema programmatically using annotations or custom generators. Register entities, map fields and columns, link tables, then compile the schema for Cycle ORM.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Cycle ORM Alignment: Perfectly integrates with Cycle ORM, enabling declarative schema definitions (annotations or fluent APIs) instead of manual SQL migrations. Ideal for teams adopting Cycle ORM or migrating from other ORMs (e.g., Doctrine, Eloquent) to reduce schema management complexity.
  • Declarative Paradigm: Supports domain-driven schema design by defining tables/fields as PHP classes, aligning with infrastructure-as-code principles. Reduces risk of schema drift by tying definitions to application logic.
  • Schema Evolution: Enables versioned schema changes via code, critical for CI/CD pipelines and feature flags. Complements Cycle Migrations or replaces them entirely.
  • Flexibility vs. Control: Offers fine-grained control (e.g., custom column types, FK constraints, indexes) while abstracting low-level SQL. Tradeoff: Less suitable for highly specialized SQL (e.g., stored procedures, advanced indexing).
  • Composite Features: Supports STI/JTI, embedded entities, composite keys, and generated fields, making it viable for complex domain models (e.g., e-commerce, SaaS multi-tenancy).
  • Relation-Generated Foreign Keys (v2.12.2): The current release fixes FK nullability resolution when multiple relations share a single generated foreign key. Previously, schema compilation could emit a NOT NULL FK even though one of the sharing relations declared it nullable. The generator now takes the most permissive nullability across all relations sharing the constraint — the correct semantic for shared-column FK patterns (e.g., polymorphic-ish ownership, optional audit links, created_by/updated_by pairs). This is a behavioral correction, not an API change: no signatures changed, no config flags added. It tightens the reliability of the declarative model for relation-heavy domains.

Technical Risk

  • Cycle ORM Lock-in: Tight coupling with Cycle ORM may limit portability if switching ORMs later. Assess migration costs if this becomes a concern.
  • Learning Curve: Teams unfamiliar with Cycle ORM’s conventions (e.g., Registry, Compiler) may require training. Compare to existing migration tools (e.g., Laravel Migrations).
  • Limited Adoption: Low GitHub stars (15) and no dependents suggest niche usage. Validate community support and long-term maintenance. Note: activity has continued past the previously recorded June 2026 release — v2.12.2 shipped 2026-10-05, indicating an actively patched line rather than a dormant one. Adoption breadth, however, remains narrow.
  • PHP Version: Requires PHP 8.1+ (check compatibility with your stack). Recent releases address PHP 8.4 deprecations, but test thoroughly.
  • Schema Validation: Relies on Cycle ORM’s validation; edge cases (e.g., circular dependencies, unsupported DB features) may need custom generators.
  • Silent DDL Deltas on Patch Upgrades (new): Because the fix alters generated DDL output for shared-FK schemas, upgrading from 2.12.1 or earlier can produce a new diff on the next compile (a constraint flipping from NOT NULL to nullable, or vice versa in edge cases). This is the one non-trivial upgrade consideration: run PrintChanges / schema diffing before applying rather than assuming a patch release is DDL-inert. Risk is low and bounded — only schemas with relations sharing a generated FK are affected — but it should be an explicit gate in the upgrade checklist.

Key Questions

  1. ORM Strategy:

    • Is Cycle ORM already in use, or is this part of a migration plan? If not, evaluate total cost of adoption (learning curve + schema refactoring).
    • How does this compare to existing tools (e.g., Doctrine Migrations, Laravel Schema Builder) in terms of developer productivity?
  2. Schema Complexity:

    • Does the application require advanced SQL features (e.g., triggers, custom collations) not supported by Cycle ORM? If yes, assess workarounds or hybrid approaches.
    • Are there legacy schemas or procedural migrations that would complicate adoption?
    • New: Do any relations share a generated foreign key column (multiple relations mapping onto one FK, optional/required mixes)? If yes, this is the exact scenario the 2.12.2 fix targets — treat it as a must-test case and confirm expected nullability is documented per column.
  3. Team Skills:

    • Does the team have experience with Cycle ORM or declarative schema tools? If not, budget for training/ramp-up.
    • Are developers comfortable with PHP-based schema definitions vs. SQL migrations?
  4. CI/CD Integration:

    • How will schema changes be versioned and tested? (e.g., Git hooks, pre-commit checks, automated rollback).
    • Does the pipeline support schema diffing (e.g., PrintChanges generator) for safe deployments? This is now mandatory for patch upgrades to 2.12.2.
  5. Performance:

    • Are there performance concerns with dynamic schema compilation? Benchmark against existing migrations.
    • How does this impact cold starts (e.g., serverless environments)?
  6. Maintenance:

    • Who will maintain and update the package long-term? (Spiral Scout’s commitment?)
    • Are there backup plans if the package stagnates (e.g., fork, custom extensions)?

Integration Approach

Stack Fit

  • Primary Use Case: Cycle ORM applications (v3+). If using Cycle ORM, this replaces or augments traditional migrations.
  • Secondary Use Case: Greenfield projects evaluating Cycle ORM for its performance and flexibility.
  • Incompatible Stacks:
    • Doctrine ORM: Requires significant refactoring to adopt Cycle ORM.
    • Eloquent/Laravel: No direct integration; would need a custom bridge.
    • Raw SQL/PDO: Not applicable without ORM layer.

Migration Path

  1. Assessment Phase:

    • Audit existing migrations/SQL scripts for compatibility with Cycle ORM’s schema conventions.
    • Identify critical dependencies (e.g., triggers, custom functions) that may not be supported.
    • Inventory shared foreign keys across relations and record intended nullability — this is the surface exposed by 2.12.2.
  2. Pilot Migration:

    • Start with non-critical schemas (e.g., test tables, new features).
    • Convert Laravel/Eloquent migrations to Cycle ORM + Schema Builder:
      // Before (Laravel)
      Schema::create('users', function (Blueprint $table) {
          $table->id();
          $table->string('name');
      });
      
      // After (Cycle ORM + Schema Builder)
      $entity = new Definition\Entity()
          ->setRole('user')
          ->setClass(User::class)
          ->getFields()
              ->set('id', (new Definition\Field())->setType('primary'))
              ->set('name', (new Definition\Field())->setType('string(32)'));
      $registry->register($entity);
      $registry->linkTable($entity, 'default', 'users');
      
    • Use PrintChanges generator to validate schema diffs.
  3. Incremental Rollout:

    • Replace one migration file at a time with Schema Builder definitions.
    • Leverage Cycle ORM’s schema compiler to generate SQL for validation.
    • Gradually migrate relationships, indexes, and constraints, prioritising entities with multiple relations targeting the same FK.
  4. Full Adoption:

    • Deprecate legacy migrations in favor of Schema Builder.
    • Integrate with CI/CD to run schema validation on every commit.

Compatibility

  • Database Support: Works with PostgreSQL, MySQL, SQLite (Cycle ORM’s supported drivers). Test edge cases (e.g., collations, character sets).
  • Cycle ORM Version: Requires Cycle ORM v3+. Check for breaking changes in minor versions (e.g., v2.x vs. v3.x).
  • Version Floor: Treat 2.12.2 as the new minimum for any schema relying on shared, relation-generated FKs. It is a drop-in patch over 2.12.x from an API standpoint — no code changes required to adopt, only a DDL re-diff.
  • Custom Generators: Extend with custom generators for unsupported features (e.g., triggers). Example:
    $registry->addGenerator(new CustomTriggerGenerator());
    
  • Hybrid Approach: Use Schema Builder for tables and raw SQL for complex operations (e.g., partitioning).

Sequencing

  1. Setup:

    • Install dependencies:
      composer require cycle/schema-builder cycle/orm cycle/database
      
    • Configure Cycle ORM (config/database.php) and Schema Builder (bootstrap/schema.php).
  2. Define Entities:

    • Create PHP classes for entities with annotations or fluent APIs.
    • Example:
      #[ORM\Entity]
      class User {
          #[ORM\Column(type: 'primary')]
          public int $id;
      
          #[ORM\Column(type: 'string(32)')]
          public string $name;
      }
      
  3. Register Schema:

    • Compile and apply schema:
      $registry = new Registry($dbal);
      $registry->register(new UserEntityDefinition());
      $schema = (new Compiler())->compile($registry);
      $orm = $orm->withSchema(new ORM\Schema($schema));
      
  4. Validate:

    • Use PrintChanges to preview changes:
      $generator = new PrintChanges($registry, $schema);
      $generator->generate();
      
  5. Upgrade Gate (2.12.2):

    • Run composer update cycle/schema-builder to ^2.12.2.
    • Re-run PrintChanges against a shadow/preview database and review every changed constraint — expect nullable FK adjustments only where relations share a generated FK.
    • Regression-test hydration/insert paths on affected entities (an incorrectly NOT NULL FK previously surfaced as a runtime insert failure, not a compile error, so existing tests may not cover it).
  6. Automate:

    • Integrate with migration tools (e.g., run on php artisan migrate or CI triggers).

Operational Impact

Maintenance

  • Pros:
    • Version Control: Schema changes are code-reviewed and versioned alongside application logic.
    • Reduced Boilerplate: No manual SQL migrations; definitions are DRY (Don’t Repeat Yourself).
    • Type Safety: PHP types enforce schema constraints (e.g., string(32) vs. text).
    • Active Patch Line: Two releases between June and October 2026, with the latest (2.12.2) being a targeted correctness fix rather than a feature drop — a reasonable maintenance signal for a niche package.
  • Cons:
    • Dependency Management: Requires Cycle ORM updates to stay compatible. Monitor for breaking changes.
    • Debugging Complexity: Schema errors may surface later in the ORM layer (e.g., during entity hydration). Use PrintChanges for early detection.
    • Custom Logic: Complex rules (e.g., dynamic column names) may require custom generators, increasing maintenance.
    • Patch Releases Can Change DDL: 2.12.2 is proof that a PATCH bump can alter generated schema. Pin to exact versions in composer.lock, and never auto-merge schema-builder bumps without a diff review.

Support

  • Pros:
    • Centralized Definitions: All schema logic lives in one place (PHP classes), easing onboarding.
    • Tooling Integration: Works with IDE autocompletion, static analysis (Psalm), and testing frameworks.
    • Community: Spiral Scout provides documentation and GitHub support (though modest activity). Issue #86 was reported and resolved, suggesting the maintainers remain responsive to correctness defects.
  • Cons:
    • Limited Ecosystem: Few third-party plugins or integrations, and no Laravel-native package — expect to own the glue code yourself.
    • Thin Bench: Small contributor base means your team is the de facto escalation path for edge cases not covered upstream.

Scaling

  • Horizontal: Schema compilation is a build/deploy-time concern, not a request-path one — no runtime scaling impact for typical PHP-FPM deployments.
  • Cold Starts: If compiling schema at boot (serverless, container init), cache the compiled schema artifact rather than recompiling per instance.
  • Large Schemas: Complexity is O(entities × relations); the 2.12.2 fix adds a cross-relation aggregation pass over shared FKs — negligible at typical domain sizes, but benchmark if you model hundreds of mutually-referencing entities.
  • Multi-Tenancy: Schema-per-tenant models multiply compile work; generate once and reuse the artifact across tenant connections.

Failure Modes

  • Compile-Time: Circular dependencies, unsupported column types, or custom-SQL features → custom generators required.
  • Diff-Time: Silent or unexpected DDL on a patch upgrade → mitigated by mandatory PrintChanges review (see 2.12.2 above).
  • Runtime: Constraint/definition mismatch surfaces as hydration or insert failures, not schema errors — the pre-2.12.2 shared-FK nullability bug is a textbook example. Add integration tests that insert against affected tables, not just schema-compile tests.
  • Deploy-Time: Non-transactional DDL on MySQL can leave partial migrations; plan rollback scripts and blue/green or expand-contract patterns for destructive changes.

Ramp-Up

  • Estimate: ~1–2 weeks for a PHP developer already fluent in ORM concepts to become productive; 3–5 days for an existing Cycle ORM team.
  • Prerequisites: Cycle ORM fundamentals (Registry, Compiler, Definition\*), DDL semantics per target database, and the PrintChanges workflow.
  • Enablement Path:
    1. Pair on converting one low-risk entity end-to-end.
    2. Document the team's diff-review checklist (including the shared-FK regression check).
    3. Establish a version-pinning + upgrade-runbook policy, given that patch releases can move DDL.
  • Hiring: Expect to train internally; Cycle ORM + schema-builder experience is not a common screening filter.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator