Weave Code
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

Data Fixtures Laravel Package

doctrine/data-fixtures

Doctrine Data Fixtures extension for Doctrine ORM/ODM. Provides a simple, structured way to define, manage, and execute data fixtures for loading seed/test data into your database, with tooling and docs to support fixture organization and execution.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package:

    composer require doctrine/data-fixtures
    
  2. Create a fixture class (e.g., database/fixtures/UserFixture.php):

    namespace Database\Fixtures;
    
    use Doctrine\Bundle\FixturesBundle\Fixture;
    use Doctrine\Persistence\ObjectManager;
    use App\Models\User;
    
    class UserFixture extends Fixture
    {
        public function load(ObjectManager $manager)
        {
            $user = new User();
            $user->name = 'John Doe';
            $user->email = 'john@example.com';
            $manager->persist($user);
            $this->addReference('user', $user); // Reference for later use
            $manager->flush();
        }
    }
    
  3. Load fixtures via Artisan:

    php artisan db:fixtures:load
    

    (Note: Laravel doesn’t have a built-in command, so you’ll need to create a custom Artisan command or use a package like doctrine/doctrine-bundle for Symfony-like integration.)

  4. Alternative: Load programmatically (e.g., in a service or test):

    use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
    use Doctrine\Common\DataFixtures\Purger\ORMPurger;
    use Doctrine\Common\DataFixtures\Loader;
    
    $loader = new Loader();
    $loader->addFixture(new UserFixture());
    
    $purger = new ORMPurger($entityManager);
    $executor = new ORMExecutor($entityManager, $purger);
    $executor->execute($loader->getFixtures());
    

Implementation Patterns

1. Organizing Fixtures

  • Group fixtures by domain (e.g., UserFixtures, ProductFixtures) and use dependency injection to load them in order.
  • Use dependsOn() to enforce execution order:
    class ProductFixture extends Fixture
    {
        public function load(ObjectManager $manager)
        {
            // ...
        }
    
        public function getDependencies()
        {
            return [UserFixture::class]; // Runs after UserFixture
        }
    }
    

2. Reusing Data with References

  • Store entities as references for later use:
    $this->addReference('admin_user', $adminUser);
    
  • Retrieve references in other fixtures:
    $user = $this->getReference('user');
    

3. Purging and Dry Runs

  • Purge database before loading (default behavior):
    $purger = new ORMPurger($entityManager);
    $executor = new ORMExecutor($entityManager, $purger);
    
  • Dry-run mode (test without persisting):
    use Doctrine\Common\DataFixtures\Executor\DryRunORMExecutor;
    $executor = new DryRunORMExecutor($entityManager);
    

4. Bulk Loading with ArrayFixture

  • Load multiple records at once:
    use Doctrine\Common\DataFixtures\ArrayFixture;
    
    class UserArrayFixture extends ArrayFixture
    {
        public function getEntities()
        {
            return [
                ['name' => 'Alice', 'email' => 'alice@example.com'],
                ['name' => 'Bob', 'email' => 'bob@example.com'],
            ];
        }
    
        public function getEntityClass()
        {
            return User::class;
        }
    }
    

5. Integration with Laravel’s Database Migrations

  • Use fixtures after migrations in DatabaseSeeder (Laravel) or a custom Artisan command:
    // In DatabaseSeeder.php
    public function run()
    {
        $this->call([
            FixturesCommand::class, // Custom command to load fixtures
        ]);
    }
    

6. Testing Workflow

  • Load fixtures only in tests (e.g., using DatabaseMigrations and DatabaseSeeders in phpunit.xml):
    <env name="DB_DISCOVERY" value="true"/>
    <env name="DB_SEED" value="true"/>
    

Gotchas and Tips

1. Database State Management

  • Purger behavior: By default, ORMPurger deletes all entities in the database. Use cautiously in production.
  • Alternative: Implement a custom purger to target specific tables:
    use Doctrine\Common\DataFixtures\Purger\PurgerInterface;
    
    class CustomPurger implements PurgerInterface
    {
        public function purge(ObjectManager $manager)
        {
            $manager->createQuery('DELETE FROM App\Models\User')->execute();
        }
    }
    

2. Reference Resolution Pitfalls

  • Numeric references: Avoid using numeric strings (e.g., "1") as reference names—they can conflict with auto-increment IDs. Use strings like "user_1".
  • Scope references: References are fixture-scoped. If two fixtures define the same reference name, the last one wins.

3. Performance Considerations

  • Bulk inserts: For large datasets, use ArrayFixture or batch inserts to avoid memory issues.
  • Transactions: Wrap fixture loading in a transaction for atomicity:
    $manager->beginTransaction();
    try {
        $executor->execute($loader->getFixtures());
        $manager->commit();
    } catch (\Exception $e) {
        $manager->rollBack();
        throw $e;
    }
    

4. Laravel-Specific Quirks

  • EntityManager access: Laravel’s EntityManager is bound to the doctrine service. Inject it via constructor or resolve it:
    $entityManager = app('doctrine')->getManager();
    
  • Custom Artisan Command: Create a command to load fixtures:
    php artisan make:command LoadFixtures
    
    // In LoadFixturesCommand.php
    protected $signature = 'db:fixtures:load';
    protected $description = 'Load Doctrine fixtures';
    
    public function handle()
    {
        $loader = new Loader();
        $loader->addFixture(new UserFixture());
    
        $purger = new ORMPurger(app('doctrine')->getManager());
        $executor = new ORMExecutor(app('doctrine')->getManager(), $purger);
        $executor->execute($loader->getFixtures());
    }
    

5. Debugging Tips

  • Dry-run mode: Test fixture logic without persisting:
    $executor = new DryRunORMExecutor($entityManager);
    
  • Logging: Enable Doctrine logging to debug fixture execution:
    $config = Setup::createAnnotationMetadataConfiguration([__DIR__.'/../src'], true);
    $config->setProxyDir(__DIR__.'/../var/proxies');
    $config->setProxyNamespace('Proxies');
    $config->setAutoGenerateProxyClasses(true);
    
    $entityManager = EntityManager::create(['url' => 'sqlite:///:memory:'], $config);
    $entityManager->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    

6. Extending Fixtures

  • Custom Fixture Types: Extend AbstractFixture or ArrayFixture for reusable logic.
  • Event Listeners: Attach listeners to fixture events (e.g., preLoad, postLoad) via Doctrine’s event system.

7. Common Errors

  • ReferenceException: Occurs when a reference is used before it’s defined. Ensure dependsOn() or proper ordering.
  • InvalidArgumentException: Thrown if a fixture class isn’t valid (e.g., missing load() method).
  • Foreign Key Violations: If fixtures reference each other, ensure parent records exist before child records.

8. Configuration Quirks

  • Doctrine Version Compatibility: Ensure your doctrine/orm and doctrine/data-fixtures versions are compatible (e.g., v2.x of fixtures works with ORM 3.x+).
  • MongoDB/Odm: Use MongoDBPurger and MongoDBExecutor for Doctrine MongoDB ODM:
    $purger = new MongoDBPurger($dm);
    $executor = new MongoDBExecutor($dm, $purger);
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport