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

Filament Factory Action Laravel Package

codewithdennis/filament-factory-action

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require codewithdennis/filament-factory-action
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="CodeWithDennis\FilamentFactoryAction\FilamentFactoryActionServiceProvider"
    
  2. Register the Action: Add the action to your FilamentResource (e.g., ProfileResource) via the getTableActions() method:

    use CodeWithDennis\FilamentFactoryAction\Actions\FactoryAction;
    
    public static function getTableActions(): array
    {
        return [
            FactoryAction::make(),
        ];
    }
    
  3. First Use Case:

    • Navigate to the Filament admin panel table for your resource (e.g., /admin/profiles).
    • Click the "Generate" button (default label) in the table actions dropdown.
    • Confirm the modal prompt to create a test record using your model's factory.

Where to Look First

  • Factory Setup: Ensure your model has a factory defined in database/factories/. Example:
    // database/factories/ProfileFactory.php
    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'is_public' => fake()->boolean(),
        ];
    }
    
  • Resource Integration: Check the getTableActions() method in your FilamentResource to register the action.
  • Customization: Review the config/filament-factory-action.php for default settings (e.g., modal title, button label).

Implementation Patterns

Usage Patterns

  1. Basic Integration:

    // ProfileResource.php
    public static function getTableActions(Profile $record): array
    {
        return [
            FactoryAction::make()
                ->label('Create Test Profile')
                ->modalHeading('Generate Test Data'),
        ];
    }
    
  2. Dynamic Factory Selection: Use the factory() method to specify a custom factory class or state:

    FactoryAction::make()
        ->factory(ProfileFactory::new())
        ->state(fn () => ['is_public' => true]), // Override factory attributes
    
  3. Bulk Generation: Combine with Filament’s bulk actions for multi-record creation:

    public static function getTableActions(): array
    {
        return [
            FactoryAction::make()
                ->label('Generate 5 Test Records')
                ->quantity(5), // Default: 1
        ];
    }
    
  4. Conditional Visibility: Hide the action based on logic (e.g., environment):

    FactoryAction::make()
        ->visible(app()->environment('local')),
    

Workflows

  1. Test Data Setup:

    • Use the action to populate a staging database with realistic test data before migrations or feature testing.
    • Example: Generate 100 User records with varied roles for testing permissions.
  2. Demo Environments:

    • Automate test data generation in CI/CD pipelines by triggering the action via Filament’s API or console commands.
  3. Debugging:

    • Quickly spin up test records to reproduce bugs in isolation (e.g., "Why does this validation fail?").

Integration Tips

  1. Filament Policies: Restrict access to the action using Filament’s built-in policies:

    FactoryAction::make()
        ->visible(fn () => auth()->user()->can('generate-test-data')),
    
  2. Event Listeners: Trigger custom logic after record creation via the afterCreate callback:

    FactoryAction::make()
        ->afterCreate(fn (Profile $profile) => Log::info("Created test profile: {$profile->id}")),
    
  3. Factory States: Leverage factory states for reusable test scenarios:

    // ProfileFactory.php
    public function withAdmin(): self
    {
        return $this->state(['role' => 'admin']);
    }
    
    // Resource.php
    FactoryAction::make()
        ->factory(ProfileFactory::new()->withAdmin()),
    

Gotchas and Tips

Pitfalls

  1. Factory Not Found:

    • Error: Factory [Model] not defined.
    • Fix: Ensure the factory class exists (e.g., ProfileFactory) and is registered in AppServiceProvider@registerFactories.
  2. Mass Assignment Risks:

    • Gotcha: Factory attributes may override protected fields if not guarded in $fillable or $guarded.
    • Fix: Explicitly define $fillable in your model or use ->state() to whitelist attributes.
  3. Modal Overlaps:

    • Issue: The factory modal may overlap with other Filament modals (e.g., edit/create).
    • Fix: Adjust CSS via config/filament-factory-action.php:
      'modal_z_index' => 50,
      
  4. Performance:

    • Warning: Generating thousands of records may time out or lock the database.
    • Fix: Use quantity() sparingly or batch creation via queues:
      FactoryAction::make()
          ->quantity(1000)
          ->dispatchNow(), // Use Laravel queues for large batches
      

Debugging

  1. Log Factory Output: Enable debug logging in config/filament-factory-action.php:

    'debug' => env('APP_DEBUG', false),
    

    Check logs for generated attributes:

    tail -f storage/logs/laravel.log
    
  2. Validate Factory State: Use dd() in the factory’s definition() method to inspect generated data:

    public function definition(): array
    {
        $data = [
            'name' => fake()->name(),
            // ...
        ];
        dd($data); // Debug output
        return $data;
    }
    
  3. Check for Conflicts:

    • Ensure no other packages override Filament’s action classes (e.g., spatie/laravel-filament-actions).
    • Clear cached views:
      php artisan view:clear
      

Tips

  1. Custom Icons: Replace the default icon with a custom SVG:

    FactoryAction::make()
        ->icon(SvgIcon::make('heroicon-o-plus-circle')->size(20)),
    
  2. Localization: Translate labels/modals using Filament’s localization:

    FactoryAction::make()
        ->label(__('filament-factory-action::actions.create'))
        ->modalHeading(__('filament-factory-action::modals.heading')),
    
  3. Environment-Specific Factories: Dynamically switch factories based on environment:

    FactoryAction::make()
        ->factory(app()->environment('staging') ? StagingProfileFactory::new() : ProfileFactory::new()),
    
  4. Extend the Action: Create a custom action class by extending FactoryAction:

    namespace App\Actions;
    
    use CodeWithDennis\FilamentFactoryAction\Actions\FactoryAction;
    
    class CustomFactoryAction extends FactoryAction
    {
        protected string $modalHeading = 'Custom Test Data';
        // Override methods as needed
    }
    
  5. API Integration: Expose the action via Filament’s API for programmatic use:

    // routes/api.php
    Route::post('/admin/profiles/factory', [ProfileResource::class, 'factoryAction'])->name('filament.admin.resources.profiles.factory-action');
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle