PHP code example of inlayphp / imports

1. Go to this page and download the library: Download inlayphp/imports 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/ */

    

inlayphp / imports example snippets


namespace App\Imports;

use App\Models\User;
use App\Validation\UserRules;
use Inlay\Imports\ImportColumn;
use Inlay\Imports\Importer;

final class UserImporter extends Importer
{
    public function validation(): string
    {
        return UserRules::class;
    }

    public function columns(): array
    {
        return [
            ImportColumn::make('name')->'mode'] ?? null) === 'upsert' ? 'update' : 'create';
    }

    public function resolveRecord(array $data, array $options): ?User
    {
        return User::query()->where('email', $data['email'])->first();
    }

    public function authorize(array $data, mixed $record, array $options): bool
    {
        return $options['user']->can($record ? 'update' : 'create', $record ?? User::class);
    }

    public function persist(array $data, mixed $record, array $options): User
    {
        $user = $record ?? new User;
        $user->fill($data)->save();

        return $user;
    }
}

use Inlay\Imports\ImportDefinition;

$definition = ImportDefinition::make('users', app(UserImporter::class))
    ->label('Import users')
    ->endpoints(
        upload: route('imports.users.upload'),
        preview: route('imports.users.preview'),
        start: route('imports.users.start'),
        status: route('imports.users.status', '{id}'),
    )
    ->acceptedFileTypes('text/csv', '.csv')
    ->maxFileSize(10_240) // Kilobytes (10 MB)
    ->previewLimit(50)
    ->options(['mode' => 'upsert']);

return inertia('Users/Import', ['userImport' => $definition]);

use Inlay\Imports\ImportValidator;

$preview = app(ImportValidator::class)->preview(
    importer: $definition->importer(),
    rows: $rows,
    mapping: ['name' => 'Full Name', 'email' => 'Email Address'],
    limit: $definition->previewRows(),
    options: [...$definition->executionOptions(), 'user' => request()->user()],
);

use Inlay\Imports\ImportProcessor;

$result = app(ImportProcessor::class)->process(
    definition: $definition,
    rows: $rows,
    mapping: $mapping,
    options: ['user' => request()->user()],
);

$result->totalRows();
$result->successfulRows();
$result->failedRows();
$result->failures();
$csvRows = $result->failurePayload();
bash
vendor/bin/pest tests/ImportTest.php