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 Csv Laravel Package

askdkc/livewire-csv

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require askdkc/livewire-csv
    php artisan vendor:publish --provider="Askdkc\LivewireCsv\LivewireCsvServiceProvider"
    

    Publish the config file to customize default settings.

  2. First Use Case Create a Livewire component to handle CSV imports:

    php artisan make:livewire ImportUsers
    

    Add the WithCsvImport trait to your component:

    use Askdkc\LivewireCsv\Traits\WithCsvImport;
    
    class ImportUsers extends Component
    {
        use WithCsvImport;
    
        // Define your model and rules
        protected $model = \App\Models\User::class;
        protected $rules = [
            'name' => 'required|string',
            'email' => 'required|email',
        ];
    
        // Define headers (column names)
        protected $headers = ['name', 'email'];
    
        public function render()
        {
            return view('livewire.import-users');
        }
    }
    
  3. Blade Integration Use the csv-import component in your view:

    <livewire:import-users />
    

Implementation Patterns

Core Workflow

  1. Component Setup

    • Extend WithCsvImport trait in your Livewire component.
    • Define $model, $rules, and $headers (required for validation and mapping).
    • Optionally override $chunkSize (default: 100) for batch processing.
  2. Handling Large Files

    • Use queues for processing large CSVs (see Using Queues).
    • Stream file uploads to avoid memory issues:
      protected function handleFileUpload()
      {
          $this->validate([
              'csv_file' => 'required|file',
          ]);
      
          $file = $this->csv_file;
          $this->processCsv($file->getRealPath());
      }
      
  3. Validation and Mapping

    • Customize validation rules in $rules.
    • Map CSV headers to model fields via $headers array.
    • Override mapCsvRow() to transform data before saving:
      protected function mapCsvRow(array $row): array
      {
          return [
              'name' => strtolower($row['name'] ?? ''),
              'email' => strtolower($row['email'] ?? ''),
          ];
      }
      
  4. Progress Tracking

    • Use $this->progress to track import status in real-time:
      <progress value="{{ $progress }}" max="100"></progress>
      <span>{{ $progress }}%</span>
      
  5. Error Handling

    • Collect errors during import:
      protected function handleErrors()
      {
          return $this->errors->all();
      }
      
    • Display errors in the view:
      @if($errors->any())
          <div class="alert alert-danger">
              {{ implode('<br>', $errors->all()) }}
          </div>
      @endif
      

Integration Tips

  1. TALL Stack Projects

    • Use the CsvImportButton component for a pre-built upload button:
      <x-csv-import-button
          wire:model="csv_file"
          label="Import CSV"
          :rules="['required|file']"
      />
      
  2. Non-TALL Stack Projects

    • Manually include the button component:
      @livewire('csv-import-button', [
          'wireModel' => 'csv_file',
          'label' => 'Import CSV',
          'rules' => ['required|file'],
      ])
      
  3. Queue-Based Processing

    • Dispatch a job for large imports (requires queue config):
      use Askdkc\LivewireCsv\Jobs\ProcessCsvJob;
      
      protected function handleFileUpload()
      {
          ProcessCsvJob::dispatch($this->csv_file->getRealPath(), $this->model, $this->rules, $this->headers);
      }
      
    • Configure queue in .env:
      QUEUE_CONNECTION=database
      
  4. Customizing UI

    • Override default views by publishing assets:
      php artisan vendor:publish --tag=livewire-csv-views
      
    • Extend styles in resources/css/app.css.

Gotchas and Tips

Pitfalls

  1. Memory Limits

    • Large CSVs (>1MB) may hit memory limits. Use queues or chunk processing:
      protected $chunkSize = 50; // Reduce for memory efficiency
      
  2. Header Mismatches

    • Ensure $headers matches the CSV columns exactly (case-sensitive).
    • Debug with:
      protected function previewCsv(array $rows)
      {
          dd($rows); // Inspect raw CSV data
      }
      
  3. File Validation

    • Validate file types explicitly:
      protected $rules = [
          'csv_file' => 'required|file|mimes:csv,tsv,text/plain',
      ];
      
  4. Queue Stuck Jobs

    • Monitor failed jobs in failed_jobs table.
    • Retry with:
      php artisan queue:retry all
      
  5. Timeouts

    • Long-running imports may timeout. Increase max_execution_time in php.ini or use queues.

Debugging Tips

  1. Log CSV Data

    • Temporarily log rows for debugging:
      protected function mapCsvRow(array $row): array
      {
          \Log::info('CSV Row:', $row);
          return [...];
      }
      
  2. Check Queue Workers

    • Run workers in a separate terminal:
      php artisan queue:work --sleep=3 --tries=3
      
  3. Validate Rules

    • Test rules independently:
      $validator = Validator::make($row, $this->rules);
      if ($validator->fails()) {
          $this->addError($validator->errors()->first());
      }
      

Extension Points

  1. Custom Importers

    • Create reusable importers by extending the trait:
      trait WithCustomCsvImport extends WithCsvImport
      {
          protected function mapCsvRow(array $row): array
          {
              // Custom logic
              return parent::mapCsvRow($row);
          }
      }
      
  2. Post-Import Actions

    • Trigger events after import:
      protected function afterImport()
      {
          event(new \App\Events\UsersImported);
      }
      
  3. Dynamic Headers

    • Infer headers from the first row:
      protected $headers = null; // Let the package auto-detect
      
  4. Batch Processing

    • Override processChunk() for custom batch logic:
      protected function processChunk(array $chunk)
      {
          foreach ($chunk as $row) {
              $this->model::create($this->mapCsvRow($row));
          }
      }
      

Config Quirks

  1. Default Settings

    • Customize in config/livewire-csv.php:
      'chunk_size' => 200,
      'max_file_size' => '5MB',
      'allowed_mimes' => ['csv', 'tsv', 'text/plain'],
      
  2. Locale Support

    • Set app.locale in .env for localized error messages.
  3. Testing

    • Mock file uploads in tests:
      $file = UploadedFile::fake()->create('test.csv', 100, 'text/csv');
      $this->set('csv_file', $file);
      
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
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