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 Import Inline Laravel Package

camya/filament-import-inline

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require camya/filament-import-inline
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Camya\FilamentImportInline\FilamentImportInlineServiceProvider"
    
  2. First Use Case: Add the ImportInlineInput to a Filament resource form:

    use Camya\FilamentImportInline\Forms\Components\ImportInlineInput;
    
    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                ImportInlineInput::make('import_data')
                    ->jsonString() // Default importer (JSON)
                    ->label('Paste JSON/CSV Data'),
            ]);
    }
    
  3. Quick Test:

    • Open the Filament resource form.
    • Paste valid JSON or CSV data (e.g., [{"name":"John","email":"john@example.com"}] or "name,email\nJohn,john@example.com").
    • The data will auto-import into the field.

Implementation Patterns

Core Workflows

  1. JSON Import:

    ImportInlineInput::make('users')
        ->jsonString()
        ->validationRules(['required', 'array'])
        ->columnMapping([
            'name' => 'Name',
            'email' => 'Email',
        ]);
    
    • Use Case: Bulk-import structured data (e.g., user records) from a JSON string.
    • Tip: Use columnMapping to rename keys for clarity in the UI.
  2. CSV Import:

    ImportInlineInput::make('products')
        ->csvString()
        ->validationRules(['required', 'string'])
        ->separator(',')
        ->enclosure('"');
    
    • Use Case: Import tabular data (e.g., product lists) from CSV pastes.
    • Tip: Customize separator/enclosure for non-standard CSV formats.
  3. Custom Importers:

    ImportInlineInput::make('custom_data')
        ->importer(function (string $string) {
            return explode("\n", $string); // Simple newline-based importer
        })
        ->validationRules(['required', 'array']);
    
    • Use Case: Handle niche formats (e.g., key-value pairs, custom delimiters).
    • Tip: Return an array or object for consistency with other importers.

Integration Tips

  1. Form Submission Handling:

    • The imported data is treated as a string by default. Use ->validationRules() to enforce structure:
      ->validationRules(['required', 'array', 'min:1'])
      
    • For nested data, chain with ->rules() in the resource’s create()/update() methods.
  2. Dynamic Column Mapping: Dynamically map CSV/JSON keys to model attributes:

    ->columnMapping(function (array $data) {
        return collect($data)->first() // Infer from first row
            ->mapWithKeys(fn ($value, $key) => [$key => $key]);
    });
    
  3. Livewire Integration:

    • Works seamlessly with Filament’s Livewire forms. No additional setup required.
    • Use wire:model for reactive updates if needed:
      ->wireModel('imported_data')
      
  4. Error Handling:

    • Validate imported data in the resource’s rules():
      public static function rules(): array
      {
          return [
              'import_data' => ['required', 'array'],
              'import_data.*' => ['required', 'string'],
          ];
      }
      

Gotchas and Tips

Pitfalls

  1. Validation Timing:

    • Validation runs after the paste event. Ensure validationRules() matches the expected structure (e.g., array for JSON objects).
    • Fix: Test with malformed data (e.g., invalid JSON) to verify error messages.
  2. CSV Edge Cases:

    • Multi-line CSV pastes may break if not properly enclosed. Use ->enclosure('"') for safety.
    • Fix: Test with CSV containing commas in quoted fields (e.g., "name,title").
  3. Data Overwrite:

    • The field’s value is replaced on paste. Preserve existing data with:
      ->default(fn () => $this->record?->import_data ?? [])
      
  4. Performance:

    • Large imports (e.g., 10,000+ rows) may lag. Use ->debounce(500) to throttle processing:
      ->debounce(500) // Delay in ms
      

Debugging Tips

  1. Log Importer Output: Add a temporary importer to debug:

    ->importer(function (string $string) {
        \Log::debug('Raw input:', [$string]);
        return json_decode($string, true);
    })
    
  2. Validation Errors:

    • Check Filament’s Livewire logs (storage/logs/laravel.log) for validation failures.
    • Tip: Use ->validationAttribute('Imported Data') for clearer error labels.
  3. Custom Importer Quirks:

    • Ensure your importer returns a consistent type (e.g., always array or object).
    • Fix: Add type checks:
      ->importer(function (string $string) {
          return is_array(json_decode($string, true)) ? json_decode($string, true) : [];
      })
      

Extension Points

  1. Custom UI Feedback: Override the default success/error messages:

    ->successMessage('Data imported successfully!')
    ->errorMessage('Invalid data format. Please check your input.')
    
  2. Pre-Import Processing: Use ->beforeImport() to transform data before validation:

    ->beforeImport(function (array $data) {
        return array_map('strtolower', $data);
    })
    
  3. Post-Import Actions: Trigger actions after import (e.g., dispatch events):

    ->afterImport(function (array $data) {
        event(new DataImported($data));
    })
    
  4. Localization: Translate messages via Filament’s language files:

    ->successMessage(__('filament-import-inline::messages.success'))
    
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat