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 Quick Add Select Laravel Package

cocosmos/filament-quick-add-select

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require cocosmos/filament-quick-add-select
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Cocosmos\FilamentQuickAddSelect\FilamentQuickAddSelectServiceProvider"
    
  2. First Use Case: Modify an existing Select component with a relationship to enable quick creation:

    Select::make('profession_id')
        ->relationship('profession', 'name')
        ->quickAdd() // <-- Add this line
    

    Now users can type a new profession name (e.g., "Data Architect") and select the "+ Add 'Data Architect'" option to instantly create and select it.

Where to Look First

  • Demo: Check the screenshot in the README for visual workflow.
  • Config: Review config/filament-quick-add-select.php for customization (e.g., creation logic, validation).
  • Events: Explore HasQuickAdd trait and QuickAdd class to understand how creation is triggered.

Implementation Patterns

Core Workflow

  1. Integration: Attach ->quickAdd() to any Select with a relationship:

    Select::make('category_id')
        ->relationship('category', 'title')
        ->quickAdd();
    
    • Supports both belongsTo and morphTo relationships.
  2. Custom Creation Logic: Override the default creation behavior by binding a closure:

    Select::make('role_id')
        ->relationship('role', 'name')
        ->quickAdd(fn (string $searchTerm) => [
            'name' => $searchTerm,
            'permissions' => ['create'], // Custom fields
        ]);
    
  3. Validation: Use the config to enforce rules (e.g., minimum length):

    // config/filament-quick-add-select.php
    'validation' => [
        'min_length' => 3,
        'required_fields' => ['name'],
    ],
    
  4. Dynamic Options: Combine with options() for hybrid selects:

    Select::make('status')
        ->options(['active', 'inactive'])
        ->quickAdd(); // Allows adding custom statuses
    
  5. Form Submission: The package handles creation during form submission. No extra steps are needed for the user.

Advanced Patterns

  • Conditional Quick Add: Disable for specific cases using a closure:

    ->quickAdd(fn () => auth()->user()->can('create_items'))
    
  • Event Hooks: Listen for creation events to log or modify data:

    use Cocosmos\FilamentQuickAddSelect\Events\QuickAddCreated;
    
    QuickAddCreated::subscribe(function (QuickAddCreated $event) {
        logger()->info("Created {$event->model} via quick add");
    });
    
  • Multi-Field Creation: Extend the model’s fillable and update the closure:

    ->quickAdd(fn (string $term) => [
        'name' => $term,
        'slug' => Str::slug($term),
        'is_active' => true,
    ]);
    

Gotchas and Tips

Pitfalls

  1. Relationship Mismatch:

    • Issue: quickAdd() fails if the relationship model doesn’t match the expected structure.
    • Fix: Ensure the relationship’s model has a field matching the search term (e.g., name for ->quickAdd()).
    • Debug: Check config/filament-quick-add-select.php for creation_field (defaults to name).
  2. Validation Errors:

    • Issue: Custom validation rules may block creation silently.
    • Fix: Override the default validator or handle exceptions:
      ->quickAdd(fn (string $term) => [
          'name' => $term,
      ])->afterStateUpdated(fn (callable $set, $state) => {
          if ($state === null) {
              $set('name', 'Default Fallback');
          }
      });
      
  3. Concurrent Edits:

    • Issue: Race conditions if multiple users create the same record.
    • Fix: Use unique() in the creation closure or implement upsert logic:
      ->quickAdd(fn (string $term) => [
          'name' => $term,
      ])->afterStateUpdated(fn ($set, $state) => {
          if ($state === null) {
              $model = Model::firstOrCreate(['name' => $term]);
              $set($model->id);
          }
      });
      
  4. Caching:

    • Issue: Quick-added items may not appear in cached lists (e.g., options()).
    • Fix: Clear relevant caches after creation or use dynamic options:
      ->options(fn () => Model::query()->where('name', 'like', '%'.$searchTerm.'%')->get())
      

Debugging Tips

  • Log Creation: Enable debug mode in config:

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

    Check logs for creation attempts.

  • Test with dd(): Inspect the $searchTerm and creation payload:

    ->quickAdd(fn (string $term) => {
        dd($term); // Debug input
        return ['name' => $term];
    });
    
  • Check Events: Listen for QuickAddAttempted and QuickAddFailed events to trace issues.

Extension Points

  1. Custom UI: Override the "+ Add" label or icon via config:

    'add_option_label' => 'Create "{term}"',
    'add_option_icon' => 'heroicon-o-plus',
    
  2. Async Creation: Use Laravel queues to defer creation:

    ->quickAdd(fn (string $term) => [
        'name' => $term,
        '_queue' => 'quick-add',
    ]);
    
  3. Permission Gates: Restrict quick-add functionality:

    ->quickAdd(fn () => auth()->user()->can('manage_items'))
    
  4. Localization: Translate labels and messages:

    'messages' => [
        'created' => 'Created "{term}"',
    ],
    

Pro Tips

  • Bulk Creation: Combine with Select::make()->multiple() to allow adding multiple related items at once.

  • Soft Deletes: Ensure the relationship model supports soft deletes if using them:

    ->quickAdd()->withGlobalSearch()->withoutTrashed();
    
  • Performance: For large datasets, use ->searchable() and limit the search term length in config:

    'validation' => [
        'max_length' => 50,
    ],
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony