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

aatis/fixtures

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require aatis/fixtures
    

    Add the bundle to your config/bundles.php (Symfony) or register the service provider in config/app.php (Laravel via bridge if applicable):

    // Laravel (if using Symfony bridge)
    $provider = new Aatis\Fixtures\FixturesServiceProvider();
    $this->registerServiceProvider($provider);
    
  2. Basic Fixture Definition Create a fixture file (e.g., database/fixtures/users.yml):

    App\Models\User:
      - { name: 'John Doe', email: '[email protected]' }
      - { name: 'Jane Smith', email: '[email protected]' }
    
  3. First Load Run the loader via Artisan (if CLI integration is set up):

    php artisan fixtures:load
    

    (Note: CLI integration may require custom setup; see "Implementation Patterns" for alternatives.)


Where to Look First

  • Documentation: Check the GitHub README for Symfony-specific setup (Laravel users may need to adapt).
  • Fixtures Directory: Defaults to database/fixtures/ (configurable). Organize files by model or domain.
  • Loader Command: If CLI support is added, inspect app/Console/Kernel.php for custom commands.

First Use Case: Seeding Development Data

  1. Define a fixture for App\Models\Post in database/fixtures/posts.yml:
    App\Models\Post:
      - { title: 'First Post', content: 'Hello World' }
      - { title: 'Second Post', content: 'Fixtures are great' }
    
  2. Load fixtures:
    php artisan fixtures:load --path=database/fixtures/posts.yml
    
    (Verify CLI command exists; may need manual instantiation of FixturesLoader.)

Implementation Patterns

Workflows

  1. Fixtures as Code

    • Store fixture files in version control (e.g., database/fixtures/).
    • Use branching to manage environment-specific data (e.g., fixtures/staging/, fixtures/prod/).
  2. Dynamic Fixture Loading Load fixtures conditionally in routes/web.php or service providers:

    use Aatis\Fixtures\FixturesLoader;
    
    public function boot()
    {
        $loader = new FixturesLoader();
        $loader->load('database/fixtures/users.yml');
    }
    
  3. Fixtures + Factories Combine with Laravel’s factories for hybrid testing:

    // Fixture (database/fixtures/users.yml)
    App\Models\User:
      - { name: 'Factory User', email: '[email protected]', password: '$2y...' }
    
    // Factory (DatabaseSeeder.php)
    User::factory()->create(['email' => '[email protected]']);
    

Integration Tips

  1. Laravel-Specific Adaptations

    • Override the loader to use Laravel’s Artisan facade:
      use Illuminate\Support\Facades\Artisan;
      
      Artisan::call('fixtures:load', [
          'path' => 'database/fixtures/users.yml',
      ]);
      
    • Extend the FixturesLoader to support Laravel’s Eloquent models natively.
  2. Environment-Aware Loading Use Laravel’s .env to control fixture loading:

    if (env('APP_ENV') === 'testing') {
        $loader->load('database/fixtures/testing/*.yml');
    }
    
  3. Fixtures + Migrations Load fixtures after migrations in DatabaseSeeder.php:

    public function run()
    {
        Artisan::call('migrate:fresh');
        $loader = new FixturesLoader();
        $loader->load('database/fixtures/');
    }
    
  4. Referencing Fixtures Use YAML anchors/aliases for relationships:

    App\Models\User:
      - &user1 { name: 'Alice', email: '[email protected]' }
    
    App\Models\Post:
      - { title: 'Welcome', user: *user1 }
    

Gotchas and Tips

Pitfalls

  1. No Native Laravel Support

    • The package is Symfony-first. Expect to:
      • Manually instantiate FixturesLoader.
      • Adapt model namespaces (e.g., App\Models\User vs. Symfony’s App\Entity\User).
    • Workaround: Create a Laravel wrapper class extending FixturesLoader.
  2. CLI Command Missing

    • The fixtures:load command may not exist. Register it in AppServiceProvider:
      public function boot()
      {
          if ($this->app->runningInConsole()) {
              $this->commands([
                  new \Aatis\Fixtures\Console\LoadFixturesCommand(),
              ]);
          }
      }
      
  3. YAML Parsing Quirks

    • Complex YAML (e.g., nested arrays) may fail silently. Validate with:
      php artisan fixtures:validate database/fixtures/users.yml
      
    • Tip: Use yaml-online-parser to debug.
  4. Foreign Key Constraints

    • Fixtures may violate constraints if loaded out of order. Use onDuplicateKeyUpdate in MySQL or transactions:
      DB::beginTransaction();
      try {
          $loader->load('fixtures/');
          DB::commit();
      } catch (\Exception $e) {
          DB::rollBack();
          throw $e;
      }
      

Debugging

  1. Enable Debug Mode Set FixturesLoader debug mode:

    $loader = new FixturesLoader();
    $loader->setDebug(true); // Logs SQL and errors
    
  2. Check Loaded Data Inspect the database or use Tinker:

    php artisan tinker
    >>> App\Models\User::all();
    
  3. Validate Fixtures Run a dry load to check syntax:

    $loader->load('fixtures/users.yml', true); // Dry run
    

Extension Points

  1. Custom Fixture Formats Extend Aatis\Fixtures\Loader\LoaderInterface to support JSON/XML:

    class JsonFixturesLoader implements LoaderInterface
    {
        public function load(string $path): void
        {
            $data = json_decode(file_get_contents($path), true);
            // Custom logic...
        }
    }
    
  2. Pre/Post-Load Hooks Subscribe to events (if the package supports them) or wrap the loader:

    $loader = new FixturesLoader();
    $loader->setPreLoadCallback(function () {
        // Reset auto-increment IDs
        DB::statement('ALTER TABLE users AUTO_INCREMENT = 1');
    });
    
  3. Fixture Factories Dynamically generate fixtures from models:

    $loader->addFactory(new class implements FixtureFactory {
        public function create(): array
        {
            return [
                'name' => 'Dynamic User',
                'email' => '[email protected]',
            ];
        }
    });
    

Config Quirks

  1. Default Path Override the default fixtures path in a config file (e.g., config/fixtures.php):

    return [
        'paths' => [
            database_path('fixtures'),
            database_path('seeds/fixtures'), // Custom path
        ],
    ];
    
  2. Model Mapping If models aren’t autodetected, configure mappings:

    # config/fixtures.php
    'mappings' => [
        'App\Models\User' => 'users',
        'App\Models\Post' => 'posts',
    ],
    
  3. Environment Variables Use .env to toggle fixture loading:

    FIxtures_ENABLED=true
    
    if (env('Fixtures_ENABLED') === 'true') {
        $loader->load('fixtures/');
    }
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle