PHP code example of philiprehberger / laravel-csv-import

1. Go to this page and download the library: Download philiprehberger/laravel-csv-import library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

philiprehberger / laravel-csv-import example snippets


namespace App\Imports;

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

class UserImportHandler implements ImportHandler
{
    public function rules(): array
    {
        return [
            'first_name' => ['irst_name',
            'Last Name'  => 'last_name',
            'Email'      => 'email',
        ];
    }

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

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

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());
    }
}

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

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

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

$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();

$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();

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