Installation
composer require askdkc/livewire-csv
php artisan vendor:publish --provider="Askdkc\LivewireCsv\LivewireCsvServiceProvider"
Publish the config file to customize default settings.
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');
}
}
Blade Integration
Use the csv-import component in your view:
<livewire:import-users />
Component Setup
WithCsvImport trait in your Livewire component.$model, $rules, and $headers (required for validation and mapping).$chunkSize (default: 100) for batch processing.Handling Large Files
protected function handleFileUpload()
{
$this->validate([
'csv_file' => 'required|file',
]);
$file = $this->csv_file;
$this->processCsv($file->getRealPath());
}
Validation and Mapping
$rules.$headers array.mapCsvRow() to transform data before saving:
protected function mapCsvRow(array $row): array
{
return [
'name' => strtolower($row['name'] ?? ''),
'email' => strtolower($row['email'] ?? ''),
];
}
Progress Tracking
$this->progress to track import status in real-time:
<progress value="{{ $progress }}" max="100"></progress>
<span>{{ $progress }}%</span>
Error Handling
protected function handleErrors()
{
return $this->errors->all();
}
@if($errors->any())
<div class="alert alert-danger">
{{ implode('<br>', $errors->all()) }}
</div>
@endif
TALL Stack Projects
CsvImportButton component for a pre-built upload button:
<x-csv-import-button
wire:model="csv_file"
label="Import CSV"
:rules="['required|file']"
/>
Non-TALL Stack Projects
@livewire('csv-import-button', [
'wireModel' => 'csv_file',
'label' => 'Import CSV',
'rules' => ['required|file'],
])
Queue-Based Processing
queue config):
use Askdkc\LivewireCsv\Jobs\ProcessCsvJob;
protected function handleFileUpload()
{
ProcessCsvJob::dispatch($this->csv_file->getRealPath(), $this->model, $this->rules, $this->headers);
}
.env:
QUEUE_CONNECTION=database
Customizing UI
php artisan vendor:publish --tag=livewire-csv-views
resources/css/app.css.Memory Limits
protected $chunkSize = 50; // Reduce for memory efficiency
Header Mismatches
$headers matches the CSV columns exactly (case-sensitive).protected function previewCsv(array $rows)
{
dd($rows); // Inspect raw CSV data
}
File Validation
protected $rules = [
'csv_file' => 'required|file|mimes:csv,tsv,text/plain',
];
Queue Stuck Jobs
failed_jobs table.php artisan queue:retry all
Timeouts
max_execution_time in php.ini or use queues.Log CSV Data
protected function mapCsvRow(array $row): array
{
\Log::info('CSV Row:', $row);
return [...];
}
Check Queue Workers
php artisan queue:work --sleep=3 --tries=3
Validate Rules
$validator = Validator::make($row, $this->rules);
if ($validator->fails()) {
$this->addError($validator->errors()->first());
}
Custom Importers
trait WithCustomCsvImport extends WithCsvImport
{
protected function mapCsvRow(array $row): array
{
// Custom logic
return parent::mapCsvRow($row);
}
}
Post-Import Actions
protected function afterImport()
{
event(new \App\Events\UsersImported);
}
Dynamic Headers
protected $headers = null; // Let the package auto-detect
Batch Processing
processChunk() for custom batch logic:
protected function processChunk(array $chunk)
{
foreach ($chunk as $row) {
$this->model::create($this->mapCsvRow($row));
}
}
Default Settings
config/livewire-csv.php:
'chunk_size' => 200,
'max_file_size' => '5MB',
'allowed_mimes' => ['csv', 'tsv', 'text/plain'],
Locale Support
app.locale in .env for localized error messages.Testing
$file = UploadedFile::fake()->create('test.csv', 100, 'text/csv');
$this->set('csv_file', $file);
How can I help you explore Laravel packages today?