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

Foundry Laravel Package

zenstruck/foundry

Foundry makes fixture creation enjoyable with an expressive, auto-completable, on-demand factory system for Symfony and Doctrine. Create and persist objects with minimal data, use factories in DoctrineFixturesBundle or tests, and support ORM, MongoDB ODM, or both.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Symfony/Laravel Alignment: Foundry is designed for Symfony ecosystems (Doctrine ORM/ODM) but is highly compatible with Laravel via the Zenstruck/FoundryBundle (or manual integration). Its factory pattern aligns with Laravel’s native create()/factory() methods, reducing cognitive overhead.
  • Domain-Driven Design (DDD) Support: Expressive factory methods (e.g., published(), withAuthor()) mirror DDD language, making fixtures self-documenting and maintainable in complex domains.
  • Event-Driven Hooks: The #[AsFoundryHook] attribute and event dispatching enable granular control over fixture lifecycle (e.g., pre/post-persistence logic), useful for side effects like notifications or caching.
  • Hybrid Persistence: Supports both Doctrine ORM (SQL) and MongoDB ODM, allowing mixed-data testing without vendor lock-in.

Integration Feasibility

  • Laravel Compatibility:
    • Doctrine ORM: Native support via doctrine/orm + doctrine/doctrine-bundle (Laravel uses doctrine/dbal under the hood, but ORM integration is seamless).
    • Eloquent: Foundry can wrap Eloquent models via custom factories, though direct ORM integration is preferred for full feature parity (e.g., auto-refresh, relationships).
    • Testing Frameworks: Works with PHPUnit (via Zenstruck/FoundryBundle) and Pest (via community packages like pestphp/foundry).
  • Migration Path:
    • Replace Laravel’s Factory facade with Foundry factories (e.g., PostFactory::new() instead of Post::factory()).
    • Leverage auto-completion for IDE support (vs. manual make:factory scaffolding).
    • Backward Compatibility: Foundry v2+ deprecates legacy traits (ResetDatabase) but provides migration guides.

Technical Risk

  • Doctrine Dependency: Heavy reliance on Doctrine ORM/ODM may introduce complexity if the project uses Eloquent-only or raw SQL. Mitigation: Use Foundry for core entities and fall back to Eloquent factories for peripheral models.
  • Learning Curve:
    • Hooks/Events: Advanced features (e.g., #[AsFoundryHook]) require understanding of Symfony’s event system, which may be unfamiliar to Laravel devs.
    • Auto-Refresh: Doctrine’s auto-refresh mechanism (for relationship consistency) can conflict with Laravel’s lazy-loading or custom repositories. Test thoroughly with withoutDoctrineEvents().
  • Performance:
    • Auto-Refresh Overhead: Enabled by default, which may slow down tests with large datasets. Disable via auto_refresh: false in config.
    • Faker Seed Management: Global seed handling (via FOUNDRY_FAKER_SEED) can cause flaky tests if not scoped properly (e.g., per-test-case seeds).

Key Questions

  1. ORM vs. Eloquent: Will the project use Foundry for all models (Doctrine ORM) or a hybrid approach (Foundry + Eloquent)? Hybrid requires additional factory wrappers.
  2. Test Isolation: How will Foundry’s auto-reset database feature interact with Laravel’s DatabaseMigrations or DatabaseTransactions? (Foundry v2.9+ deprecates ResetDatabase trait in favor of built-in reset mechanisms.)
  3. CI/CD Impact: Foundry’s Docker-based test suite suggests local dev setup may require Docker (though Laravel’s Valet/Sail can mitigate this).
  4. Legacy Code: How will existing make:factory fixtures migrate to Foundry’s syntax? Tooling like php artisan foundry:upgrade (if available) or custom scripts may be needed.
  5. Monitoring: Foundry lacks built-in analytics for fixture usage. Will custom logging be required to track factory performance or failures?

Integration Approach

Stack Fit

  • Primary Use Case: Test Data Generation (unit/integration tests) and Doctrine Fixtures (e.g., php bin/console doctrine:fixtures:load).
  • Laravel Synergy:
    • Replace create()/factory() with Foundry’s fluent methods (e.g., UserFactory::new()->admin()->create()).
    • Use Foundry’s State objects for reusable fixture states (e.g., PublishedState, DraftState).
    • Leverage auto-completion for IDE hints (vs. Laravel’s make:factory scaffolding).
  • Symfony Additions:
    • DoctrineFixturesBundle: Foundry integrates natively, enabling complex fixture loading (e.g., ordered dependencies).
    • Event Dispatching: Useful for testing Symfony-specific features (e.g., KernelEvents, DoctrineEvents).

Migration Path

  1. Pilot Phase:
    • Start with 1–2 critical models (e.g., User, Post) to test Foundry’s expressiveness.
    • Compare performance vs. Laravel’s native factories (benchmark create() vs. Factory::new()->create()).
  2. Tooling:
    • Use php artisan foundry:make:factory (if available) or adapt Laravel’s make:factory to output Foundry syntax.
    • Example migration script:
      // Before (Laravel)
      $user = User::factory()->admin()->create();
      
      // After (Foundry)
      $user = UserFactory::new()->admin()->create();
      
  3. Configuration:
    • Add to composer.json:
      "require-dev": {
          "zenstruck/foundry": "^2.10",
          "zenstruck/foundry-bundle": "^2.10"
      }
      
    • Configure in config/packages/zenstruck_foundry.yaml:
      zenstruck_foundry:
          auto_refresh: true # Enable for relationship consistency
          faker_seed: random # Or 'fixed' for reproducible tests
      
  4. Testing Framework:
    • For PHPUnit: Use Zenstruck/FoundryBundle with FoundryExtension.
    • For Pest: Install pestphp/foundry and configure in pest.php:
      uses(FoundryTestCase::class)->in('Feature');
      

Compatibility

Feature Laravel Native Foundry Support Notes
Factory Methods ✅ ✅ Fluent syntax (->admin()).
Relationships ✅ ✅ Auto-refresh ensures consistency.
State Management ❌ ✅ Reusable states (e.g., PublishedState).
Doctrine Fixtures ❌ ✅ Integrates with DoctrineFixturesBundle.
Faker Customization ✅ ✅ Extend FoundryFaker class.
Test Isolation ✅ (Transactions) ✅ (Auto-Reset) Foundry v2.9+ has built-in reset.
Event Hooks ❌ ✅ #[AsFoundryHook] attribute.

Sequencing

  1. Phase 1: Core Models
    • Migrate User, Post, Product factories to Foundry.
    • Replace factory() calls in tests with Factory::new().
  2. Phase 2: Relationships
    • Enable auto_refresh: true and test bidirectional relationships (e.g., User->Posts).
    • Use withoutDoctrineEvents() in unit tests to avoid event overhead.
  3. Phase 3: Fixtures & CI
    • Integrate with DoctrineFixturesBundle for bulk data loading.
    • Configure Foundry’s reset mechanism in CI (e.g., DATABASE_RESET_MODE=migrate).
  4. Phase 4: Advanced Features
    • Implement custom hooks for side effects (e.g., caching, notifications).
    • Explore #[AsFoundryHook] for complex lifecycle logic.

Operational Impact

Maintenance

  • Pros:
    • Self-Documenting Fixtures: Factory methods (e.g., ->published()->withTags()) act as living documentation.
    • Reduced Boilerplate: No need for make:factory scaffolding or manual Faker setup.
    • IDE Support: Auto-completion for factory methods and states.
  • Cons:
    • Doctrine Dependency: Maintenance burden if using Eloquent-only or raw SQL.
    • Hook Complexity: Custom hooks/events require understanding of Symfony’s event system.
    • Version Pinning: Foundry’s rapid releases (e.g., v2.10.1) may require frequent updates to avoid deprecation warnings.

Support

  • Debugging:
    • Factory Debugging: Use Factory::debug() to inspect generated data.
    • Event Debugging: Foundry’s event system can be verbose; use `withoutDoctrine
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.
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table