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

Eloquent Populator Laravel Package

guidocella/eloquent-populator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require --dev guidocella/eloquent-populator
    

    Ensure the package is in require-dev for testing environments.

  2. Basic Usage Add use GuidoCella\EloquentPopulator\Populator; to your factory. Call Populator::guessFormatters($this->modelName()) in the definition() method:

    public function definition(): array
    {
        return Populator::guessFormatters($this->modelName());
    }
    
  3. First Use Case For a User model with columns first_name, email, and created_at, the factory will auto-generate:

    [
        'first_name' => $faker->firstName(),
        'email' => $faker->unique()->safeEmail(),
        'created_at' => $faker->dateTime(),
    ]
    

Implementation Patterns

Usage Patterns

  1. Merging Custom Attributes Override auto-generated values for specific columns:

    public function definition(): array
    {
        return array_merge(
            Populator::guessFormatters($this->modelName()),
            ['status' => 'active'] // Custom override
        );
    }
    
  2. Handling Relationships Populate BelongsTo relationships automatically:

    // UserFactory.php
    public function definition(): array
    {
        return Populator::guessFormatters($this->modelName());
    }
    // Auto-generates a related `Role` if defined in the User model.
    
  3. Multilingual Support If using laravel-multilingual, translatable fields generate locale-specific arrays:

    // Auto-generates:
    ['title' => ['en' => 'Sample Title', 'it' => 'Titolo Esempio']]
    
  4. Conditional Population Use Populator::guessFormatters() in state methods:

    public function admin()
    {
        return $this->state(fn(array $attributes) => [
            ...Populator::guessFormatters($this->modelName()),
            'role' => 'admin',
        ]);
    }
    

Workflows

  • Database Schema Changes No need to update factories manually—Populator infers new columns dynamically.
  • Testing Workflow Use in DatabaseTests or FeatureTests to avoid hardcoding test data:
    $user = User::factory()->create(); // Auto-populated
    

Integration Tips

  • Custom Formatters Extend the package by publishing and overriding config:

    php artisan vendor:publish --provider="GuidoCella\EloquentPopulator\PopulatorServiceProvider"
    

    Modify config/eloquent-populator.php to add custom column-to-formatter mappings.

  • Seeding Combine with Laravel’s DatabaseSeeder for bulk data:

    User::factory()->count(100)->create(); // Auto-populated
    

Gotchas and Tips

Pitfalls

  1. Column Name Ambiguity

    • Issue: Populator may misguess formatters for ambiguous column names (e.g., name could map to firstName() or lastName()).
    • Fix: Override in definition() or add custom mappings in config.
  2. Reserved Keywords

    • Issue: Columns named created_at or updated_at are handled automatically, but custom timestamps may conflict.
    • Fix: Explicitly define them in definition() if needed.
  3. Relationships Without Factories

    • Issue: Populator creates BelongsTo relationships, but if the related model lacks a factory, it fails.
    • Fix: Ensure all related models have factories or use Populator::skipRelationships().
  4. Performance

    • Issue: Guessing formatters for large tables may slow down factory creation.
    • Fix: Cache results or use Populator::guessFormatters($modelName, true) for one-time generation.

Debugging

  • Inspect Guessed Formatters Temporarily log the output to verify mappings:

    dd(Populator::guessFormatters($this->modelName()));
    
  • Check Database Schema Ensure column names/types match expectations (e.g., VARCHAR vs. TEXT for text() formatter).

Config Quirks

  • Custom Formatters Extend the formatters array in config/eloquent-populator.php:

    'formatters' => [
        'custom_column' => fn(Faker $faker) => $faker->uuid,
    ],
    
  • Excluded Columns Skip specific columns (e.g., password):

    Populator::guessFormatters($this->modelName(), [], ['password']);
    

Extension Points

  1. Custom Guesser Implement GuidoCella\EloquentPopulator\Contracts\ColumnGuesser to add logic for niche use cases.

  2. Event Listeners Hook into eloquent-populator.guessing or eloquent-populator.guessed events for real-time modifications:

    Event::listen('eloquent-populator.guessed', function ($model, $attributes) {
        $attributes['custom_field'] = 'hardcoded';
    });
    
  3. Testing Mock Populator in unit tests:

    $this->partialMock(Populator::class, ['guessFormatters'])
         ->shouldReceive('guessFormatters')
         ->andReturn(['key' => 'value']);
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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