philiprehberger/laravel-csv-import 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

philiprehberger/laravel-csv-import

Composer 安装命令:

composer require philiprehberger/laravel-csv-import

包简介

Chunked CSV import with row-level validation, error collection, dry-run mode, and queue support

README 文档

README

Tests Latest Version on Packagist Last updated

Chunked CSV import with row-level validation, error collection, dry-run mode, and queue support.

Requirements

  • PHP 8.2+
  • Laravel 11 or 12

Installation

composer require philiprehberger/laravel-csv-import

The service provider is registered automatically via Laravel's package auto-discovery.

Optionally publish the config file:

php artisan vendor:publish --tag=csv-import-config

Usage

1. Create an Import Handler

Implement PhilipRehberger\CsvImport\Contracts\ImportHandler:

namespace App\Imports;

use App\Models\User;
use PhilipRehberger\CsvImport\Contracts\ImportHandler;

class UserImportHandler implements ImportHandler
{
    public function rules(): array
    {
        return [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name'  => ['required', 'string', 'max:255'],
            'email'      => ['required', 'email', 'max:255'],
        ];
    }

    public function map(array $row): array
    {
        return [
            'First Name' => 'first_name',
            'Last Name'  => 'last_name',
            'Email'      => 'email',
        ];
    }

    public function handle(array $row): void
    {
        User::create($row);
    }

    public function uniqueBy(): ?string
    {
        return 'email';
    }
}

2. Run the Import

use PhilipRehberger\CsvImport\CsvImporter;

$result = CsvImporter::make('/path/to/users.csv')
    ->using(UserImportHandler::class)
    ->chunkSize(500)
    ->import();

echo "Imported: {$result->successCount}";
echo "Errors:   {$result->errorCount}";

if ($result->hasErrors()) {
    foreach ($result->getErrors() as $error) {
        echo "Line {$error->lineNumber}: " . implode(', ', $error->errors->all());
    }
}

Dry-Run Mode

$result = CsvImporter::make('/path/to/users.csv')
    ->using(UserImportHandler::class)
    ->dryRun();

Queue Support

CsvImporter::make('/path/to/users.csv')
    ->using(UserImportHandler::class)
    ->chunkSize(1000)
    ->importQueued();

Importing an Uploaded File

$result = CsvImporter::fromUpload($request->file('csv'))
    ->using(UserImportHandler::class)
    ->import();

Progress Tracking

$result = CsvImporter::make('/path/to/users.csv')
    ->using(UserImportHandler::class)
    ->chunkSize(500)
    ->onChunkComplete(function (int $chunkIndex, int $processedRows, int $successCount, int $errorCount) {
        echo "Chunk {$chunkIndex}: {$processedRows} rows, {$successCount} ok, {$errorCount} failed\n";
    })
    ->import();

Column Transforms

Apply transformations to mapped columns before validation:

$result = CsvImporter::make('/path/to/users.csv')
    ->using(UserImportHandler::class)
    ->transformColumn('email', fn (string $value) => strtolower($value))
    ->transformColumn('first_name', fn (string $value) => trim($value))
    ->import();

Changing the Delimiter

CsvImporter::make($path)
    ->using(MyHandler::class)
    ->delimiter(';')
    ->import();

API

CsvImporter (Fluent Builder)

Method Description
CsvImporter::make(string $path) Create an importer from a file path
CsvImporter::fromUpload(UploadedFile $file) Create an importer from an uploaded file
->using(string $handlerClass) Set the import handler class
->chunkSize(int $size) Set chunk size (default: config value)
->delimiter(string $delimiter) Set CSV delimiter
->enclosure(string $enclosure) Set CSV enclosure character
->onChunkComplete(callable $callback) Register a per-chunk progress callback
->transformColumn(string $column, callable $transformer) Register a pre-validation column transformer
->import() Run import synchronously
->dryRun() Validate all rows without persisting
->importQueued() Dispatch import as a background job

ImportHandler Interface

Method Description
rules(): array Laravel validation rules for each mapped row
map(array $row): array Map CSV headers to attribute names
handle(array $row): void Persist a single validated row
uniqueBy(): ?string Attribute name for duplicate detection, or null to disable

ImportResult

Property / Method Type Description
$totalRows int Total data rows in the file
$successCount int Rows successfully handled
$errorCount int Rows that failed validation or handling
$skippedCount int Rows skipped due to duplicate detection
hasErrors() bool True if errorCount > 0
getErrors() RowError[] All collected row errors
toArray() array Serialisable summary

Events

Event Payload
ImportStarted $path, $totalRows, $isDryRun
ImportChunkProcessed $path, $chunkIndex, $rowsInChunk, $successCount, $errorCount, $skippedCount
ImportCompleted $path, $result (ImportResult), $isDryRun

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

philiprehberger/laravel-csv-import 适用场景与选型建议

philiprehberger/laravel-csv-import 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 62 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「queue」 「csv」 「import」 「validation」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 philiprehberger/laravel-csv-import 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 philiprehberger/laravel-csv-import 我们能提供哪些服务?
定制开发 / 二次开发

基于 philiprehberger/laravel-csv-import 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 62
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 32
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-09