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

Laravel Doctrine Factory Laravel Package

nolanos/laravel-doctrine-factory

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require stemble/laravel-doctrine-factory
    
  2. Add the Trait Annotate your Doctrine entity with @ORM\Entity and add the HasFactory trait:

    use Doctrine\ORM\Mapping as ORM;
    use Stemble\DoctrineFactory\HasFactory;
    
    #[ORM\Entity]
    class User
    {
        use HasFactory;
        // ...
    }
    
  3. Generate a Factory Create a factory class in database/factories (e.g., UserFactory.php):

    namespace Database\Factories;
    
    use Stemble\DoctrineFactory\Factory;
    
    class UserFactory extends Factory
    {
        protected $model = User::class;
    
        public function definition()
        {
            return [
                'name' => 'John Doe',
                'email' => 'john@example.com',
            ];
        }
    }
    
  4. First Use Case Create a user in tests or migrations:

    use Database\Factories\UserFactory;
    
    $user = UserFactory::new()->create();
    

Implementation Patterns

Workflows

  1. Basic Creation

    // Single entity
    $user = UserFactory::new()->create();
    
    // Multiple entities
    $users = UserFactory::new()->count(5)->create();
    
  2. State Management Define states in the factory:

    class UserFactory extends Factory
    {
        public function admin()
        {
            return $this->state([
                'role' => 'admin',
                'is_active' => true,
            ]);
        }
    }
    

    Usage:

    $admin = UserFactory::new()->admin()->create();
    
  3. Relationships Use has() and for() helpers:

    class PostFactory extends Factory
    {
        public function definition()
        {
            return ['title' => 'Test Post'];
        }
    }
    
    // Create a user with posts
    $user = UserFactory::new()
        ->has(Post::class, 3)
        ->create();
    
  4. Sequences Generate sequential data:

    class UserFactory extends Factory
    {
        protected static function definition()
        {
            return [
                'email' => 'user_' . self::$sequence . '@example.com',
            ];
        }
    }
    
  5. Callbacks Use afterMaking and afterCreating:

    class UserFactory extends Factory
    {
        protected function afterMaking()
        {
            $this->sequence('email');
        }
    }
    

Integration Tips

  • Testing: Replace Eloquent factories in tests with Doctrine equivalents.
  • Migrations: Use factories to seed test databases.
  • API Testing: Generate realistic test data for endpoints.
  • Custom Logic: Extend factories with custom methods for domain-specific logic.

Gotchas and Tips

Pitfalls

  1. Entity Manager Binding Ensure the Doctrine Entity Manager is bound in the service container:

    $this->app->bind(\Doctrine\ORM\EntityManagerInterface::class, function ($app) {
        return $app->make('doctrine.orm.entity_manager');
    });
    
  2. Transaction Handling Factories create entities in a transaction by default. For bulk operations, disable transactions:

    $users = UserFactory::new()->count(100)->disableTransactions()->create();
    
  3. Sequence Conflicts Avoid reusing sequences across unrelated factories to prevent ID collisions.

  4. Missing HasFactory Trait Forgetting to add use Stemble\DoctrineFactory\HasFactory; will cause runtime errors.

Debugging

  • Factory Not Found: Verify the factory class is in database/factories and follows naming conventions (UserFactory for User entity).
  • Undefined Properties: Ensure all factory-defined fields match the entity’s mapped properties.
  • Relationship Errors: Check that has() and for() relationships reference valid factory classes.

Config Quirks

  • Default Factory Path: Factories are auto-discovered in database/factories. Customize via:
    'factories' => [
        'paths' => [app_path('Factories')],
    ],
    
    in config/doctrine-factory.php.

Extension Points

  1. Custom States Dynamically define states via state() or predefine them in the factory class.

  2. Factory Macros Add reusable logic:

    UserFactory::macro('withRole', function ($role) {
        return $this->state(['role' => $role]);
    });
    

    Usage:

    $user = UserFactory::new()->withRole('editor')->create();
    
  3. Override Defaults Use afterMaking to modify attributes post-creation:

    protected function afterMaking()
    {
        $this->model->setPassword(Hash::make('password'));
    }
    
  4. Custom Model Binding Override $model in the factory for polymorphic entities:

    protected $model = function () {
        return User::class; // or dynamic logic
    };
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope