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

davidbadura/fixtures

Flexible PHP fixtures library with YAML/JSON/TOML/PHP loaders, Faker support, automatic dependency resolution, configurable converters, tagging/filtering, validation via events, expression language, and persisters for Doctrine ORM/MongoDB and Propel.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require davidbadura/fixtures
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Davidbadura\Fixtures\FixturesServiceProvider"
    
  2. Basic Fixture Loading Define a fixture in database/fixtures/ (e.g., users.yml):

    users:
      - { id: 1, name: 'John Doe', email: 'john@example.com' }
      - { id: 2, name: 'Jane Doe', email: null } # Nullable fields now supported
    

    Load fixtures in a Laravel test or command:

    use Davidbadura\Fixtures\Fixtures;
    
    $fixtures = new Fixtures();
    $fixtures->load('users');
    
  3. First Use Case: Seeding Tests Use in phpunit.xml or setUp():

    public function setUp(): void
    {
        parent::setUp();
        $this->artisan('db:seed', ['--class' => 'FixturesTestSeeder']);
    }
    

Implementation Patterns

Workflow: Fixture-Based Development

  1. Define Fixtures Store fixtures in database/fixtures/ (supports .yml, .json, .php). Example: roles.json

    {
      "roles": [
        { "id": 1, "name": "Admin" },
        { "id": 2, "name": "Editor", "description": null } # Nullable fields
      ]
    }
    
  2. Load with Dependency Resolution Use Fixtures::load() with dependency chains:

    $fixtures->load(['users', 'roles']); // Loads in order
    $fixtures->load('posts', ['author_id' => 1]); // Dynamic references
    
  3. Validation & Error Handling Validate fixtures via config (config/fixtures.php):

    'validation' => [
        'users.*' => [
            'required' => ['name', 'email'],
            'nullable' => ['email'] // Explicitly allow nulls
        ]
    ],
    
  4. Integration with Laravel

    • Artisan Command:
      $this->call('fixtures:load', ['fixtures' => 'users,posts']);
      
    • Service Provider: Bind Fixtures to the container:
      $this->app->bind('fixtures', function ($app) {
          return new Fixtures($app['config']);
      });
      
  5. Dynamic Fixtures with Nullable Fields Generate fixtures programmatically with nullable values:

    $fixtures->add('dynamic_users', [
        ['name' => 'Alice', 'email' => 'alice@example.com'],
        ['name' => 'Bob', 'email' => null] // Nullable fields
    ]);
    

Gotchas and Tips

Pitfalls

  1. Dependency Order Matters

    • Fixtures with unresolved references (e.g., post.author_id) will fail silently or throw cryptic errors.
    • Fix: Load parent fixtures first or use Fixtures::loadWithDependencies().
  2. Nullable Field Handling

    • While nullable fields are now supported, ensure your validation rules account for them:
      'validation' => [
          'users.*' => [
              'nullable' => ['email', 'description'] // Explicitly declare nullable fields
          ]
      ],
      
    • Tip: Use nullable in validation rules to avoid strictness errors.
  3. Config Overrides

    • Published config (config/fixtures.php) may conflict with package defaults.
    • Tip: Merge configs explicitly:
      $fixtures = new Fixtures(config(['fixtures' => $customConfig]));
      
  4. Archived Package Risks

    • No updates since 2022 (except minor fixes); fork or maintain locally if critical.
    • Workaround: Extend the class or submit PRs to the original repo.

Debugging Tips

  1. Enable Verbose Logging Set in config:

    'debug' => true,
    

    Logs fixture loading steps to storage/logs/laravel.log.

  2. Check Fixture Paths Default paths are database/fixtures/ and tests/fixtures/. Override via config:

    'paths' => [
        database => 'custom/fixtures/path',
    ],
    
  3. Test Fixture Isolation Use transactions in tests:

    public function tearDown(): void
    {
        DB::transaction(function () {
            DB::table('users')->truncate();
        });
    }
    

Extension Points

  1. Custom Fixture Types Extend Davidbadura\Fixtures\Fixtures to support new formats (e.g., CSV):

    class ExtendedFixtures extends Fixtures {
        public function loadCsv(string $fixture) { /* ... */ }
    }
    
  2. Hooks for Post-Loading Use events (if supported) or wrap Fixtures::load():

    $fixtures->load('users');
    event(new FixturesLoaded('users'));
    
  3. Database-Specific Logic Override getConnection() to target specific databases:

    $fixtures->setConnection('mysql_secondary');
    
  4. Nullable Field Validation Customize validation for nullable fields in config/fixtures.php:

    'validation' => [
        'posts.*' => [
            'nullable' => ['published_at', 'excerpt'],
            'required_if' => ['published_at', 'excerpt', 'is_published']
        ]
    ],
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky