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

Laravel Csv Laravel Package

coderflex/laravel-csv

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require coderflex/laravel-csv
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Coderflex\LaravelCsv\LaravelCsvServiceProvider" --tag="config"
    
  2. First Use Case:

    • For a Livewire component, add the importer to your view:
      @livewire('csv-importer', ['model' => \App\Models\YourModel::class])
      
    • For a standalone button (TALL stack):
      <x-csv-import-button :model="\App\Models\YourModel" />
      
  3. Key Files to Review:

    • config/laravel-csv.php (for chunk size, queue settings, etc.)
    • app/Http/Livewire/CsvImporter.php (default component logic)
    • resources/views/vendor/laravel-csv/ (blade templates)

Implementation Patterns

Core Workflows

  1. Livewire Integration:

    • Extend the base importer for custom logic:
      namespace App\Http\Livewire;
      
      use Coderflex\LaravelCsv\Livewire\CsvImporter as BaseImporter;
      
      class CustomCsvImporter extends BaseImporter {
          protected $rules = [
              'file' => 'required|mimes:csv,txt',
          ];
      
          public function import() {
              $this->validate();
              $this->processFile($this->file->getRealPath(), \App\Models\YourModel::class);
          }
      }
      
    • Use processFile() for default handling or override handleRow() for custom row processing.
  2. Queue-Based Processing:

    • Configure chunk size in config/laravel-csv.php:
      'chunk_size' => 1000, // Adjust based on server memory
      
    • Dispatch jobs manually:
      use Coderflex\LaravelCsv\Jobs\ProcessCsvChunk;
      
      ProcessCsvChunk::dispatch($filePath, \App\Models\YourModel::class, $chunk);
      
  3. TALL Stack Integration:

    • Use the provided Blade components:
      <x-csv-import-form :model="\App\Models\YourModel" />
      
    • Customize the form via Tailwind classes or publish views:
      php artisan vendor:publish --tag="laravel-csv-views"
      
  4. Validation & Mapping:

    • Define rules in your Livewire component:
      protected $rules = [
          'file' => 'required|mimes:csv',
          'column_mapping' => 'sometimes|array',
      ];
      
    • Map CSV columns to model fields:
      public function getColumnMapping() {
          return [
              'csv_column_name' => 'model_attribute',
          ];
      }
      

Gotchas and Tips

Common Pitfalls

  1. Memory Issues:

    • Problem: Large CSV files may exhaust memory if chunking is misconfigured.
    • Fix: Start with chunk_size = 500 and monitor server logs. Use queues ('use_queue' => true) for files >100K rows.
  2. Column Mismatches:

    • Problem: CSV headers may not align with model fields.
    • Fix: Override getColumnMapping() or use auto_map: true in config:
      'auto_map' => true, // Auto-detects column names (e.g., "first_name" → "firstName")
      
  3. Livewire State Persistence:

    • Problem: Uploaded file disappears after page refresh.
    • Fix: Store the file path temporarily in a session or database:
      session(['csv_temp_path' => $file->getRealPath()]);
      
  4. Queue Stuck Jobs:

    • Problem: Jobs fail silently due to misconfigured queues.
    • Fix: Check failed_jobs table and ensure:
      • Queue worker is running (php artisan queue:work).
      • Database connection is correct in .env.

Debugging Tips

  • Log Rows: Add debug logs in handleRow():
    \Log::debug('Processing row:', ['data' => $row, 'model' => $model]);
    
  • Validate CSV: Use League\Csv\Reader to inspect the file before processing:
    $csv = Reader::createFromPath($filePath, 'r');
    $csv->setHeaderOffset(0);
    $records = $csv->getRecords();
    
  • Test with Small Files: Start with a 10-row CSV to verify logic before scaling.

Extension Points

  1. Custom Importers:

    • Create a trait for reusable logic:
      trait HandlesCustomCsv {
          protected function validateRow(array $row) {
              // Custom validation
          }
      }
      
  2. Post-Import Actions:

    • Hook into imported() event in your Livewire component:
      protected $listeners = ['imported' => 'notifyUser'];
      
      public function notifyUser() {
          toast()->success('Import completed!');
      }
      
  3. Batch Processing:

    • Use processInBatches() for large datasets:
      $this->processInBatches($filePath, \App\Models\YourModel::class, 5000);
      
  4. Progress Tracking:

    • Extend the base component to track progress:
      public $progress = 0;
      
      protected function incrementProgress() {
          $this->progress += ($this->totalRows / 100);
          $this->emit('progress', $this->progress);
      }
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor