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

Livewire Fakeable Laravel Package

tomeasterbrook/livewire-fakeable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require tomeasterbrook/livewire-fakeable
    
  2. Publish the config (optional, but recommended for customization):
    php artisan vendor:publish --provider="TomEasterbrook\LivewireFakeable\LivewireFakeableServiceProvider"
    
  3. Use in a Livewire component: Add a $fakeable property to your component class, defining fake data for each property:
    use TomEasterbrook\LivewireFakeable\Traits\Fakeable;
    
    class UserProfile extends Component
    {
        use Fakeable;
    
        public $name = '';
        public $email = '';
        public $isActive = false;
    
        protected $fakeable = [
            'name' => \Faker\Factory::create()->name,
            'email' => \Faker\Factory::create()->email,
            'isActive' => fn() => rand(0, 1) === 1,
        ];
    
        public function mount()
        {
            // Your mount logic here
        }
    

First Use Case

Scenario: You're building a UserProfile component and want to avoid hardcoding placeholder data in mount(). Solution: Define $fakeable properties once, and the package auto-populates them during local development only if the property is empty.


Implementation Patterns

Core Workflow

  1. Define Fake Data: Use $fakeable to declare fake data for properties. Supports:

    • Static values (e.g., 'status' => 'draft').
    • Faker methods (e.g., 'name' => fn() => \Faker\Factory::create()->name).
    • Closures (e.g., 'isActive' => fn() => rand(0, 1) === 1).
  2. Integration with Livewire Lifecycle: The package hooks into mount() and populates empty properties only in local environments (configurable via .env or config file).

    protected $fakeable = [
        'posts' => fn() => collect()->times(5, fn() => [
            'title' => \Faker\Factory::create()->sentence,
            'content' => \Faker\Factory::create()->paragraph,
        ]),
    ];
    
  3. Conditional Fake Data: Use closures to generate dynamic fake data based on other properties:

    protected $fakeable = [
        'user' => fn() => [
            'name' => \Faker\Factory::create()->name,
            'email' => \Faker\Factory::create()->unique()->email,
            'posts' => fn() => collect()->times($this->user['postCount'] ?? 3, fn() => [...]),
        ],
    ];
    
  4. Testing: Mock the fakeable trait in tests to ensure deterministic behavior:

    $component = new UserProfile();
    $component->fakeable = []; // Disable faking in tests
    

Advanced Patterns

  • Reusable Fake Data: Create a helper class to centralize fake data logic:

    class FakeDataHelper {
        public static function fakeUser(): array {
            return [
                'name' => \Faker\Factory::create()->name,
                'email' => \Faker\Factory::create()->email,
            ];
        }
    }
    

    Then use it in $fakeable:

    protected $fakeable = [
        'user' => FakeDataHelper::fakeUser(),
    ];
    
  • Environment-Specific Faking: Override the shouldFake() method to control when faking occurs:

    public function shouldFake(): bool {
        return app()->environment('local') && !app()->runningUnitTests();
    }
    
  • Nested Fake Data: Handle nested arrays/objects by using closures:

    protected $fakeable = [
        'profile' => fn() => [
            'address' => [
                'street' => \Faker\Factory::create()->streetAddress,
                'city' => \Faker\Factory::create()->city,
            ],
        ],
    ];
    

Gotchas and Tips

Pitfalls

  1. Overwriting Existing Data: The package only populates empty properties. If a property is set in mount() or via user input, it won’t be overwritten. Debug Tip: Use dd($this->fakeable) to verify what’s being generated.

  2. Faker Initialization: Faker is initialized per-property. For performance, reuse a single Faker instance:

    protected $fakeable = [
        'name' => fn() => $this->faker->name,
        'email' => fn() => $this->faker->email,
    ];
    

    Initialize $this->faker in mount():

    public function mount() {
        $this->faker = \Faker\Factory::create();
    }
    
  3. Closure Scope: Closures in $fakeable run in the context of the component. Avoid relying on undefined properties:

    // ❌ Avoid: Uses undefined $this->userId
    'user' => fn() => User::find($this->userId)->fake(),
    

    Fix: Pass dependencies explicitly or use static methods.

  4. Testing Quirks: Fake data may interfere with unit tests. Disable it explicitly:

    public function shouldFake(): bool {
        return false; // Disable in tests
    }
    
  5. Performance: Avoid expensive operations (e.g., database queries) in $fakeable closures. Keep it lightweight for rapid iteration.

Debugging Tips

  • Log Fake Data: Add a method to inspect what’s being generated:

    public function debugFakeable() {
        dd($this->fakeable);
    }
    

    Call it in mount() to verify behavior.

  • Check Environment: Ensure APP_ENV=local is set when testing fake data. The package respects this by default.

  • Validate Faker: If Faker methods fail (e.g., unique() conflicts), reset the Faker instance:

    $this->faker = \Faker\Factory::create();
    

Extension Points

  1. Custom Fake Providers: Extend the package by creating a custom fake provider:

    class CustomFakeProvider {
        public function fakeCustomData() {
            return ['custom_field' => \Faker\Factory::create()->uuid];
        }
    }
    

    Then integrate it into $fakeable:

    protected $fakeable = [
        'custom' => (new CustomFakeProvider())->fakeCustomData(),
    ];
    
  2. Dynamic Fake Data: Use the fake() helper method to generate data on demand:

    public function mount() {
        $this->fakeData = $this->fake(['key' => fn() => \Faker\Factory::create()->word]);
    }
    
  3. Conditional Fake Logic: Override shouldFake() to add custom conditions:

    public function shouldFake(): bool {
        return parent::shouldFake() && $this->isDemoMode();
    }
    
  4. Global Fake Overrides: Publish the config and override fakeable_environments to control which environments use fake data:

    'fakeable_environments' => ['local', 'staging'],
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
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