PHP code example of jhonoryza / laravel-import-tables

1. Go to this page and download the library: Download jhonoryza/laravel-import-tables 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/ */

    

jhonoryza / laravel-import-tables example snippets




namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\UserImport;
use Jhonoryza\LaravelImportTables\Repositories\ImportRepository;
use Jhonoryza\LaravelImportTables\Services\ImportProgress;

class ImportController extends Controller
{
    /**
     * get all import data
     */
    public function index(Request $request, ImportRepository $repo)
    {
        $imports = $repo->getList(
            status: $request->get('status'),
            module: $request->get('module'),
            limit: 50
        );

        return response()->json($imports);
    }

    /**
     * get specific import data
     */
    public function show($id, ImportRepository $repo)
    {
        $import = $repo->getById($id);

        return response()->json($import);
    }

    /**
     * import function
     */
    public function store(Request $request)
    {
        $request->validate([
            'file'   => '     $data = Excel::toArray([], $file)[0]; // First Sheet
        $emails = collect($data)
            ->skip(1) // skip header
            ->pluck(0) // first column
            ->filter();

        $duplicates = $emails
            ->values()
            ->duplicates();

        if ($duplicates->isNotEmpty()) {
            $message = 'Duplicate mails in Excel file: ' . $duplicates->join(', ');
            session()->flash('failed', $message);
            throw ValidationException::withMessages([]);
        }
        $emails = $emails->all();

        $duplicates = DB::table('users')
            ->select('email')
            ->whereNull('deleted_at')
            ->whereIn('email', $emails)
            ->get();

        if ($duplicates->isNotEmpty()) {
            $duplicateCount = $duplicates->count();
            $displayLimit = 5;

            if ($duplicateCount > $displayLimit) {
                $codesToDisplay = $duplicates->take($displayLimit)->implode('email', ', ');
                $message = "There is {$duplicateCount} duplicate mails. some example: {$codesToDisplay}, ...";
            } else {
                $codesToDisplay = $duplicates->implode('email', ', ');
                $message = "Duplicate mails founded: {$codesToDisplay}";
            }
            session()->flash('failed', $message);
            throw ValidationException::withMessages([]);
        }
    }
}



namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\ShouldQueue;
use Maatwebsite\Excel\Events\AfterChunk;
use Maatwebsite\Excel\Events\AfterImport;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Validators\Failure;
use App\Models\User;
use Jhonoryza\LaravelImportTables\Services\ImportProgress;

class UserImport implements ToModel, WithHeadingRow, WithChunkReading, WithBatchInserts, WithEvents, ShouldQueue, SkipsEmptyRows, WithValidation, SkipsOnFailure
{
    use SkipsFailures;
    use Importable;

    private string $identifier;

    public function __construct(string $identifier)
    {
        $this->identifier = $identifier;
    }

    public function batchSize(): int
    {
        return 500;
    }

    public function chunkSize(): int
    {
        return 1000;
    }

    public function rules(): array
    {
        return [
            '*.name' => [
                '}
}

public function collection(Collection $collection)
{
    $rows = $collection->map(fn($row) => [
        'is_receive_repeatedly' => 1,
        'voucher_id' => $this->voucherId,
        'code' => $row['code'],
        'allocation' => 1,
        'created_at' => now(),
        'updated_at' => now(),
    ])->toArray();

    try{
        DB::beginTransaction();

        VoucherCode::insert($rows);

        DB::commit();

        ImportProgress::make($this->identifier)
            ->incrementOk(count($rows))
            ->pushOkMessage("Inserted " . count($rows) . " rows");

    } catch (Throwable $th) {
        DB::rollBack();

        ImportProgress::make($this->identifier)
            ->incrementFail($collection->count())
            ->pushFailMessage("Error: " . $th->getMessage());
    }
}
bash
php artisan migrate