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

Data Fixture Laravel Package

phpmob/data-fixture

Lightweight PHP package for defining and loading data fixtures to seed databases during development and testing. Helps generate consistent sample records, manage fixture sets, and reset data quickly for repeatable test runs and local environments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require phpmob/data-fixture
    
  2. Define a fixture class (e.g., UserFixture):
    use Phpmob\DataFixture\Fixture\AbstractFixture;
    
    class UserFixture extends AbstractFixture
    {
        public function load()
        {
            return [
                'users' => [
                    [
                        'name' => 'John Doe',
                        'email' => 'john@example.com',
                    ],
                    [
                        'name' => 'Jane Smith',
                        'email' => 'jane@example.com',
                    ],
                ],
            ];
        }
    }
    
  3. Load fixtures via CLI:
    php artisan fixture:load UserFixture
    
    (Note: If no fixture:load command exists, check for fixture:run or create a custom Artisan command.)

First Use Case

Use this to seed a local development database with test data before running Laravel’s migrate:fresh or db:seed. Example workflow:

php artisan migrate:fresh --seed
php artisan fixture:load UserFixture PostFixture

Implementation Patterns

Fixture Organization

  1. Group fixtures by feature/module:
    /database/fixtures/
    ├── auth/
    │   ├── UserFixture.php
    │   └── RoleFixture.php
    ├── blog/
    │   ├── PostFixture.php
    │   └── CommentFixture.php
    └── FixtureLoader.php  # Custom loader (optional)
    
  2. Leverage dependency injection in fixtures:
    class PostFixture extends AbstractFixture
    {
        protected $userFixture;
    
        public function __construct(UserFixture $userFixture)
        {
            $this->userFixture = $userFixture;
        }
    
        public function load()
        {
            $this->userFixture->load(); // Load users first
            return [
                'posts' => [
                    ['title' => 'First Post', 'user_id' => 1],
                ],
            ];
        }
    }
    

Workflows

  1. Batch Loading:

    php artisan fixture:load UserFixture PostFixture --batch
    

    (If --batch isn’t supported, chain fixtures manually in a custom command.)

  2. Conditional Loading:

    class EnvironmentAwareFixture extends AbstractFixture
    {
        public function load()
        {
            if (app()->environment('local')) {
                return $this->getLocalData();
            }
            return $this->getStagingData();
        }
    }
    
  3. Integration with Laravel Seeder: Extend Laravel’s DatabaseSeeder to use phpmob/data-fixture:

    class DatabaseSeeder extends Seeder
    {
        public function run()
        {
            $loader = new \Phpmob\DataFixture\FixtureLoader();
            $loader->load([new UserFixture(), new PostFixture()]);
        }
    }
    

Testing Patterns

  • Unit Test Fixtures:
    public function test_user_creation()
    {
        $loader = new FixtureLoader();
        $loader->load([new UserFixture()]);
    
        $this->assertDatabaseHas('users', ['email' => 'john@example.com']);
    }
    
  • Reset Fixtures Between Tests: Use a trait to clean fixtures post-test:
    trait CleansFixtures
    {
        protected function tearDown(): void
        {
            Artisan::call('fixture:reset');
            parent::tearDown();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. No Built-in Artisan Command: The package lacks a default fixture:load command. Workaround: Create a custom command:

    php artisan make:command FixtureLoadCommand
    
    // app/Console/Commands/FixtureLoadCommand.php
    public function handle()
    {
        $fixtures = $this->argument('fixtures');
        $loader = new \Phpmob\DataFixture\FixtureLoader();
        $loader->load(array_map(function ($class) {
            return new $class();
        }, explode(',', $fixtures)));
    }
    

    Register it in app/Console/Kernel.php:

    protected $commands = [
        \App\Console\Commands\FixtureLoadCommand::class,
    ];
    
  2. No Transaction Support: Fixtures are loaded directly to the DB. Tip: Wrap loading in a transaction for safety:

    DB::transaction(function () {
        $loader->load([new UserFixture()]);
    });
    
  3. Outdated Package: Last release in 2018. Mitigations:

    • Fork and update dependencies (e.g., PHP 8.x support).
    • Use as a reference and pair with modern tools like Laravel Factories or Mockerize.

Debugging Tips

  1. Verify Fixture Data: Add a dump() in load() to inspect payloads:

    public function load()
    {
        $data = [
            'users' => [...]
        ];
        dump($data); // Debug output
        return $data;
    }
    
  2. Check for Duplicate Keys: Ensure fixture data doesn’t conflict with existing records. Use upsert or ignore flags:

    public function load()
    {
        return [
            'users' => [
                ['email' => 'john@example.com', 'ignore' => true], // Skip if exists
            ],
        ];
    }
    

Extension Points

  1. Custom Fixture Loaders: Override Phpmob\DataFixture\FixtureLoader to add logic (e.g., logging, pre-processing):

    class CustomLoader extends FixtureLoader
    {
        public function load(array $fixtures)
        {
            Log::info('Loading fixtures: ' . implode(', ', array_keys($fixtures)));
            parent::load($fixtures);
        }
    }
    
  2. Dynamic Fixture Data: Fetch data from APIs or config:

    class ApiUserFixture extends AbstractFixture
    {
        public function load()
        {
            $users = Http::get('https://api.example.com/users')->json();
            return ['users' => $users];
        }
    }
    
  3. Integration with Laravel Events: Trigger events after fixture loading:

    event(new FixturesLoaded($fixtures));
    

    Listen in EventServiceProvider:

    protected $listen = [
        FixturesLoaded::class => [
            HandleFixturePostLoad::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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope