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

Fixture Handler Laravel Package

dansan/fixture-handler

Laravel helper for managing fixtures/test data. Load, reset, and organize fixture sets to seed databases quickly during development and automated tests, keeping sample data consistent across environments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require --dev dansan/fixture-handler
    

    Register the service provider in config/app.php under providers:

    Dansan\FixtureHandler\FixtureHandlerServiceProvider::class,
    
  2. Basic Usage Place fixtures in database/fixtures/ (e.g., users.json, posts.json). Define a test case extending Dansan\FixtureHandler\TestCase:

    use Dansan\FixtureHandler\TestCase;
    
    class UserTest extends TestCase
    {
        protected $fixtures = ['users', 'posts'];
    
        public function testUserCreation()
        {
            $user = User::first();
            $this->assertNotNull($user);
        }
    }
    
  3. First Run Execute tests with:

    php artisan test
    

    Fixtures are auto-loaded before each test method.


Implementation Patterns

Fixture Organization

  • Directory Structure
    database/
    ├── fixtures/
    │   ├── users.json
    │   ├── posts.json
    │   └── relationships/
    │       └── user_posts.json  # For polymorphic relationships
    
  • Naming Conventions Use snake_case for fixture files (e.g., roles_and_permissions.json). Group related fixtures in subdirectories (e.g., database/fixtures/admin/).

Workflow Integration

  1. Seeding vs. Fixtures Use fixtures for test-specific data (e.g., mock users, edge cases). Use Laravel’s DatabaseSeeder for shared test data (e.g., default roles).

  2. Dynamic Fixtures Load fixtures conditionally based on test methods:

    public function testAdminFeatures()
    {
        $this->loadFixtures(['admin/users']);
        // Test logic...
    }
    
  3. Fixture Factories Combine with Laravel’s factories for dynamic data:

    // In a fixture file (users.json)
    {
        "data": [
            {"name": "John", "email": "{{ $this->faker->unique()->safeEmail }}"}
        ]
    }
    
  4. Test Isolation Use refreshDatabase() in setUp() to ensure clean state:

    public function setUp(): void
    {
        parent::setUp();
        $this->artisan('migrate:fresh');
        $this->loadFixtures($this->fixtures);
    }
    

Advanced Patterns

  • Fixture Dependencies Define dependencies in a meta.json file:

    {
        "users": ["roles"],
        "posts": ["users"]
    }
    

    Load them in order:

    $this->loadFixtures(['roles', 'users', 'posts']);
    
  • Custom Fixture Loaders Extend Dansan\FixtureHandler\Loaders\LoaderInterface for custom formats (e.g., YAML):

    class YamlLoader implements LoaderInterface
    {
        public function load(string $path): array
        {
            return yaml_parse_file($path);
        }
    }
    

    Register in config/fixture-handler.php:

    'loaders' => [
        'yaml' => \App\Loaders\YamlLoader::class,
    ],
    

Gotchas and Tips

Common Pitfalls

  1. Fixture Overwriting

    • Issue: Running tests multiple times may overwrite existing data.
    • Fix: Use migrate:fresh or refreshDatabase() to reset the database.
  2. Missing Dependencies

    • Issue: Fixtures referencing non-existent models (e.g., role_id in users.json).
    • Fix: Load dependent fixtures first or use null as a placeholder.
  3. JSON Validation

    • Issue: Malformed JSON in fixture files causes silent failures.
    • Fix: Validate fixtures with:
      php artisan fixture:validate
      
  4. Case Sensitivity

    • Issue: Model names in fixtures must match exactly (e.g., User vs. user).
    • Fix: Use snake_case in fixture files and studlyCase in code.

Debugging Tips

  • Log Fixtures Enable debug mode in config/fixture-handler.php:

    'debug' => true,
    

    Logs fixture loading to storage/logs/fixture-handler.log.

  • Inspect Loaded Data Dump fixtures in setUp():

    public function setUp(): void
    {
        parent::setUp();
        $this->loadFixtures($this->fixtures);
        \Log::info('Loaded fixtures:', $this->getLoadedFixtures());
    }
    
  • Partial Fixture Loading Load only specific records:

    $this->loadFixtures(['users'], ['id' => 1]); // Load only user with ID 1
    

Configuration Quirks

  1. Custom Database Connections Specify in config/fixture-handler.php:

    'connection' => 'sqlite_testing',
    
  2. Fixture File Extensions Supported: .json, .yaml (with custom loader). Tip: Use .json for consistency.

  3. Performance

    • Issue: Large fixtures slow down tests.
    • Fix: Use loadFixtures() selectively or split into smaller files.

Extension Points

  1. Custom Fixture Events Listen for fixture.loaded events:

    \Event::listen('fixture.loaded', function ($fixture) {
        \Log::info("Fixture loaded: {$fixture['name']}");
    });
    
  2. Post-Fixture Hooks Run logic after fixtures load:

    public function setUp(): void
    {
        parent::setUp();
        $this->loadFixtures($this->fixtures);
        $this->afterFixturesLoaded();
    }
    
    protected function afterFixturesLoaded()
    {
        // Example: Seed additional test data
        factory(App\Post::class)->create(['user_id' => 1]);
    }
    
  3. Fixture Encryption Encrypt sensitive data (e.g., passwords) in fixtures:

    // In a fixture file
    {
        "password": "{{ bcrypt('secret') }}"
    }
    

    Requires use Illuminate\Support\Facades\Hash; in the test class.

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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity