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

Faker Laravel Package

apie/faker

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require apie/faker
    
  2. Basic Integration:

    use Apie\Faker\ApieObjectFaker;
    use Faker\Factory;
    
    $faker = Factory::create();
    $faker->addProvider(ApieObjectFaker::createWithDefaultFakers($faker));
    
  3. First Use Case: Generate a random User entity with populated value objects:

    $user = $faker->fakeClass(User::class);
    

Where to Look First

  • README.md: Focus on the Documentation section for setup and basic usage.
  • Source: ApieObjectFaker for core logic.
  • Examples: Check the tests/ directory in the monorepo for practical use cases.

Implementation Patterns

Core Workflow

  1. Entity/Value Object Generation:

    • Use $faker->fakeClass(ClassName::class) to generate fully populated objects.
    • Example:
      $order = $faker->fakeClass(Order::class); // Generates Order with random OrderId, Customer, Items, etc.
      
  2. Value Object Handling:

    • For string-based value objects with regex constraints (e.g., Email, PhoneNumber), the package auto-generates valid values using their regex patterns.
    • Example:
      $email = $faker->fakeClass(Email::class); // Auto-generates a valid email string.
      
  3. Custom Fakers:

    • Implement ApieClassFaker for domain-specific logic:
      $faker->addProvider(new SpecificClassFaker());
      $customVo = $faker->fakeClass(SpecificValueObject::class);
      
  4. Static createRandom Methods:

    • Prefer annotating value objects with [FakeMethod("createRandom")] to avoid custom fakers:
      #[FakeMethod("createRandom")]
      class Age implements ValueObjectInterface {
          public static function createRandom(Generator $generator): self {
              return new self($generator->numberBetween(18, 99));
          }
      }
      

Integration Tips

  • Testing: Use fakeClass() in unit tests to generate test data:
    public function testUserCreation() {
        $user = $faker->fakeClass(User::class);
        $this->assertInstanceOf(FirstName::class, $user->firstName());
    }
    
  • Seeding: Combine with Laravel’s DatabaseSeeder for test databases:
    public function run() {
        $faker = Factory::create();
        $faker->addProvider(ApieObjectFaker::createWithDefaultFakers($faker));
    
        User::factory()->createMany(
            collect(range(1, 10))->map(fn(_) => $faker->fakeClass(User::class))
        );
    }
    
  • API Mocking: Generate fake responses for API tests:
    $response = $faker->fakeClass(OrderResponse::class);
    $this->json('POST', '/orders', $response->toArray());
    

Gotchas and Tips

Pitfalls

  1. Circular Dependencies:

    • If entities reference each other (e.g., User has Address, Address has User), the faker may hang or fail.
    • Fix: Use lazy loading or mock circular references in tests.
  2. Regex Validation:

    • String value objects with strict regex patterns (e.g., ^[A-Z]{2}-\d{4}$) may fail if the faker’s default strings don’t match.
    • Fix: Extend ApieObjectFaker to override regex generation:
      $faker->addProvider(new class($faker) extends ApieObjectFaker {
          protected function generateStringWithRegex(string $regex): string {
              return 'AB-1234'; // Hardcoded fallback
          }
      });
      
  3. Attribute Parsing:

    • The [FakeMethod] attribute must be on the class, not the method. Misplacement causes silent failures.
    • Fix: Verify attributes are correctly applied:
      #[FakeMethod("createRandom")]
      class MyVo { ... } // Correct
      
  4. Performance:

    • Recursive faking (deeply nested objects) can be slow. Cache fakers for repeated use:
      $cachedFaker = new ApieObjectFaker($faker);
      $faker->addProvider($cachedFaker);
      

Debugging

  • Enable Faker Debugging:
    $faker->seed(1234); // Ensures reproducible "random" data.
    
  • Log Faker Calls: Override fakeClass() to log generation:
    $faker->fakeClass = function($class) {
        \Log::info("Generating $class");
        return parent::fakeClass($class);
    };
    
  • Check Supported Classes: Use ApieObjectFaker::supports() to verify if a class is faked:
    if (!ApieObjectFaker::supports($faker, new ReflectionClass(MyClass::class))) {
        throw new \RuntimeException("No faker for MyClass");
    }
    

Extension Points

  1. Custom Providers: Add domain-specific fakers globally:

    $faker->addProvider(new class($faker) implements ApieClassFaker {
        public function supports(ReflectionClass $class): bool {
            return $class->implementsInterface(UserInterface::class);
        }
        public function fakeFor(Generator $generator, ReflectionClass $class): UserInterface {
            return new User($generator->fakeClass(FirstName::class), ...);
        }
    });
    
  2. Override Default Fakers: Replace the default provider entirely:

    $faker->addProvider(new class($faker) extends ApieObjectFaker {
        protected function getDefaultFakers(): array {
            return [new CustomStringFaker(), ...parent::getDefaultFakers()];
        }
    });
    
  3. Dynamic Fake Methods: Use attributes to conditionally enable faking:

    #[FakeMethod("createRandom", condition: fn(Generator $g) => $g->boolean(70))]
    class Discount implements ValueObjectInterface { ... }
    // Only 70% chance to use createRandom().
    
  4. Laravel Service Provider: Register the faker globally in AppServiceProvider:

    public function boot() {
        $faker = Factory::create();
        $faker->addProvider(ApieObjectFaker::createWithDefaultFakers($faker));
        app()->singleton('faker', fn() => $faker);
    }
    

    Then inject via constructor:

    public function __construct(private Faker\Generator $faker) {}
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui