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

Entity Faker Laravel Package

butschster/entity-faker

Generate fake PHP entities and persist them via your ORM using a simple factory. Define per-class attribute generators with Faker, support inheritance via raw attributes, and create single or multiple entities using Laminas hydrators/entity factories.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require butschster/entity-faker
    

    Add the service provider to config/app.php (unchanged):

    'providers' => [
        // ...
        Butschster\EntityFaker\EntityFakerServiceProvider::class,
    ],
    
  2. Basic Usage (Updated for v2.0.0):

    use Butschster\EntityFaker\EntityFaker;
    
    $faker = app(EntityFaker::class);
    $fakeUser = $faker->fake(User::class); // Generates a fake User instance via redesigned EntityFactory
    
  3. First Use Case (Updated for v2.0.0): Generate test data for a User model with a Post relationship:

    $fakeUser = $faker->fake(User::class, [
        'posts' => [Post::class, Post::class] // Array of related entities (now handled by redesigned factory)
    ]);
    

Implementation Patterns

Core Workflow (Updated for v2.0.0)

  1. Faking Entities (Redesigned Factory):

    // Single entity (now uses EntityFactory v2)
    $fakePost = $faker->fake(Post::class);
    
    // Multiple entities (batch processing optimized)
    $fakePosts = $faker->fakeMany(Post::class, 5);
    
  2. Customizing Attributes (Enhanced Rules):

    // Override defaults (now supports more flexible rule parsing)
    $fakeUser = $faker->fake(User::class, [
        'name' => 'John Doe',
        'email' => '{{email}}' // Leverages Faker's rule engine
    ]);
    
    // Dynamic attribute generation
    $fakeUser = $faker->fake(User::class, [
        'age' => '{{numberBetween(20, 60)}}'
    ]);
    
  3. Handling Relationships (Improved Resolution):

    // One-to-many (now uses redesigned relationship resolver)
    $fakeUser = $faker->fake(User::class, [
        'posts' => [Post::class, Post::class]
    ]);
    
    // Many-to-many (optimized for v2.0.0)
    $fakePost = $faker->fake(Post::class, [
        'tags' => [Tag::class, Tag::class, Tag::class]
    ]);
    
  4. Seeding with Factories (Updated for v2.0.0):

    // In a seeder (now leverages EntityFactory v2)
    public function run()
    {
        $faker = app(EntityFaker::class);
        $faker->fakeMany(User::class, 10)->each(function ($user) {
            $user->save();
        });
    }
    
  5. Integration with Tests (Unchanged):

    /** @test */
    public function test_user_creation()
    {
        $fakeUser = $this->app->make(EntityFaker::class)->fake(User::class);
        $this->assertInstanceOf(User::class, $fakeUser);
    }
    

Gotchas and Tips

Common Pitfalls (Updated for v2.0.0)

  1. Circular References (Still Applies):

    • If User has a profile relationship and Profile has a user relationship, the faker may loop infinitely.
    • Fix: Explicitly define one side or use ignoreRelationships():
      $fakeUser = $faker->fake(User::class)->ignoreRelationships(['profile']);
      
  2. Non-Serializable Attributes (Still Applies):

    • Attributes like Carbon instances or closures may cause issues.
    • Fix: Use ->withoutAttributes(['created_at', 'updated_at']) or cast them in your model.
  3. Custom Accessors/Mutators (Still Applies):

    • If your model has custom logic in getAttribute() or setAttribute(), the faker may not handle it correctly.
    • Fix: Use ->withoutAccessors() or mock the logic temporarily.
  4. Database Constraints (Still Applies):

    • Faking data for fields with unique constraints may fail.
    • Fix: Use ->ignoreConstraints() or handle duplicates manually.

Debugging Tips (Updated for v2.0.0)

  1. Inspect Generated Data (Enhanced in v2.0.0):

    $fakeData = $faker->getFakeData(User::class);
    dd($fakeData); // See raw data before instantiation (now includes factory metadata)
    
  2. Enable Verbose Mode (Optimized):

    $faker->setVerbose(true); // Logs what’s being faked (now includes factory resolution steps)
    
  3. Reset Faker State (Updated for v2.0.0):

    $faker->reset(); // Clears cached data for retries (now resets redesigned factory state)
    

Extension Points (Updated for v2.0.0)

  1. Custom Faker Rules (Enhanced in v2.0.0):

    $faker->extend('custom_rule', function () {
        return 'custom_value';
    });
    // Usage:
    $fakeUser = $faker->fake(User::class, ['bio' => '{{custom_rule}}']);
    
  2. Override Default Rules (Now Supports Factory-Specific Overrides):

    $faker->override(User::class, [
        'email' => '{{email}}@example.com' // Force domain (now applies to EntityFactory v2)
    ]);
    
  3. Event Listeners (Updated for v2.0.0):

    • Hook into entity-faker.faking or entity-faker.faked events for custom logic:
      Event::listen('entity-faker.faking', function ($entity, $attributes) {
          if ($entity instanceof User) {
              $attributes['is_active'] = true;
          }
      });
      
  4. Integration with Laravel Factories (Hybrid Approach):

    • Use the faker alongside Laravel’s built-in factories for hybrid approaches:
      $fakeUser = $faker->fake(User::class);
      User::factory()->create(['email' => $fakeUser->email]);
      

Performance Tips (Updated for v2.0.0)

  1. Batch Faking (Optimized in v2.0.0):

    $fakeUsers = $faker->fakeMany(User::class, 1000); // More efficient with redesigned factory
    
  2. Disable Relationships for Bulk Operations (Still Applies):

    $fakeUsers = $faker->fakeMany(User::class, 1000)
        ->ignoreRelationships(['posts', 'profile'])
        ->each(fn($u) => $u->save());
    
  3. Cache Faker Instances (Still Applies):

    $faker = app(EntityFaker::class); // Reuse instance in tests/seeds (now leverages v2.0.0 optimizations)
    

Breaking Changes in v2.0.0

  1. EntityFactory Redesign:

    • The internal EntityFactory class has been completely redesigned. Existing custom implementations may need updates.
    • Migration Tip: Review any custom factory logic and adapt to the new structure.
  2. Rule Parsing:

    • The way attribute rules are parsed has changed. Ensure your custom rules are compatible with the new engine.
  3. Method Signatures:

    • Some method signatures may have been adjusted for consistency. Check the updated API documentation for any changes.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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