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

Fixtures Laravel Package

apie/fixtures

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require apie/fixtures --dev
    

    Note: This package is designed for development/testing only. Exclude it from production via require-dev in composer.json.

  2. First Use Case: Test Data Generation

    use Apie\Fixtures\Factory\Factory;
    use Apie\Fixtures\Factory\FactoryBuilder;
    
    // Create a factory for a User model
    $factory = FactoryBuilder::create()
        ->withModel(\App\Models\User::class)
        ->withFaker()
        ->build();
    
    // Generate a single record
    $user = $factory->create();
    
    // Generate multiple records
    $users = $factory->createMany(5);
    
  3. Where to Look First

    • FactoryBuilder: Central class for configuring factories.
    • Fixtures Directory: /vendor/apie/fixtures/src/Fixtures/ for predefined fixtures (e.g., UserFixture, PostFixture).
    • Factory Methods: Methods like create(), createMany(), and persist() (if using database fixtures).

Implementation Patterns

Core Workflows

1. Model-Based Fixtures

// Define a custom factory for a Post model
$postFactory = FactoryBuilder::create()
    ->withModel(\App\Models\Post::class)
    ->withFaker()
    ->withState([
        'title' => 'Test Post',
        'content' => fn() => 'Content for ' . $this->faker->word,
    ])
    ->build();

$post = $postFactory->create();

2. Database Persistence

// Persist fixtures to the database (requires Eloquent)
$factory = FactoryBuilder::create()
    ->withModel(\App\Models\User::class)
    ->withFaker()
    ->withPersistence()
    ->build();

$factory->persist($user); // Single record
$factory->persistMany($users); // Multiple records

3. Relationships Between Fixtures

// Create a User with related Posts
$userFactory = FactoryBuilder::create()
    ->withModel(\App\Models\User::class)
    ->withFaker()
    ->build();

$postFactory = FactoryBuilder::create()
    ->withModel(\App\Models\Post::class)
    ->withFaker()
    ->withState(['user_id' => fn() => $userFactory->create()->id])
    ->build();

$user = $userFactory->create();
$posts = $postFactory->createMany(3);

4. Custom Fixtures

Extend Apie\Fixtures\Fixture to create domain-specific fixtures:

use Apie\Fixtures\Fixture;

class CustomFixture extends Fixture
{
    public function __construct()
    {
        $this->state([
            'custom_field' => fn() => $this->faker->unique()->word,
        ]);
    }
}

5. Integration with Laravel Testing

use Apie\Fixtures\Factory\FactoryBuilder;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->factory = FactoryBuilder::create()
            ->withModel(\App\Models\User::class)
            ->withFaker()
            ->withPersistence()
            ->build();
    }

    public function test_user_creation()
    {
        $user = $this->factory->create();
        $this->assertDatabaseHas('users', ['email' => $user->email]);
    }
}

Integration Tips

  1. Combine with Laravel Factories Use Apie\Fixtures alongside Laravel’s built-in factories for hybrid approaches:

    $factory = FactoryBuilder::create()
        ->withModel(\App\Models\User::class)
        ->withFaker()
        ->withState(fn() => \App\Models\User::factory()->raw())
        ->build();
    
  2. Seeders Load fixtures in database seeders:

    use Apie\Fixtures\Factory\FactoryBuilder;
    
    class DatabaseSeeder extends Seeder
    {
        public function run()
        {
            $factory = FactoryBuilder::create()
                ->withModel(\App\Models\User::class)
                ->withFaker()
                ->withPersistence()
                ->build();
    
            $factory->createMany(10);
        }
    }
    
  3. API Testing Generate fixtures for API endpoints:

    $user = $this->factory->create();
    $response = $this->get("/api/users/{$user->id}");
    $response->assertOk();
    

Gotchas and Tips

Pitfalls

  1. No ORM Dependency by Default

    • Fixtures are model-agnostic. Use withPersistence() explicitly for Eloquent.
    • Workaround: Implement custom persistence logic for non-Eloquent models.
  2. Faker Initialization

    • The package does not auto-initialize Faker. Always call withFaker():
      ->withFaker() // Required for faker-based state generation
      
  3. State Overrides

    • Later withState() calls overwrite previous ones. Use mergeState() for additive behavior:
      ->withState(['field' => 'value'])
      ->mergeState(['field2' => 'value2']) // Preserves 'field'
      
  4. Memory Leaks with Large Fixtures

    • createMany() loads all fixtures into memory. For large datasets, use batch processing:
      $batchSize = 100;
      for ($i = 0; $i < 1000; $i += $batchSize) {
          $factory->persistMany($factory->createMany($batchSize));
      }
      
  5. Monorepo Maintenance

    • Issues/PRs must be submitted to the Apie monorepo. The apie/fixtures repo is a proxy.

Debugging Tips

  1. Inspect Factory State Dump the factory’s current state before creation:

    dump($factory->getState());
    
  2. Enable Faker Debugging Configure Faker to log seed values:

    $factory->withFaker()->withFakerSeed(1234)->withFakerDebug();
    
  3. Validate Persistence Check if records were saved:

    $this->assertDatabaseCount('users', 1);
    
  4. Override Fixture Classes For debugging, replace a fixture class temporarily:

    $factory->withFixture(new class extends \Apie\Fixtures\Fixture {
        public function __construct() {
            $this->state(['debug_field' => 'override']);
        }
    });
    

Extension Points

  1. Custom Factory Builders Extend FactoryBuilder to add domain-specific logic:

    class CustomFactoryBuilder extends FactoryBuilder
    {
        public function withCustomState(array $state): self
        {
            $this->state($state);
            return $this;
        }
    }
    
  2. Plugin System Attach behaviors to factories via closures:

    $factory = FactoryBuilder::create()
        ->withModel(\App\Models\User::class)
        ->withFaker()
        ->onCreate(fn($model) => $model->update(['active' => true]))
        ->build();
    
  3. Fixture Events Listen for fixture creation events (requires event system integration):

    event(new FixtureCreated($fixture, $model));
    
  4. Hybrid Factories Combine with Laravel’s Model::factory() for dynamic state:

    $factory->withState(fn() => \App\Models\User::factory()->state(['role' => 'admin'])->raw());
    
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