-1

CSV report how to import a CSV file with a format like this image in laravel 7?

Previously, I was able to create a feature to import excel files in xls or xlsx format, now I want to make it for CSV format as shown above. With the code that I have created as below, I always get an error: "Undefined offset: 1" when importing the csv file.

Controller

    public function import(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|mimes:csv'
        ]);

        if ($validator->fails()) {
            return back()->with('toast_error', $validator->messages()->all()[0])->withInput();
        }

        $data = new BookedVoucher();

        $data->name = $request->name;
        $fileName = time().'_'.$request->file->getClientOriginalName();
        $filePath = $request->file('file')->storeAs('reports', $fileName, 'public');

        $data->file = $filePath;
        $data->created_by = \Auth::user()->id;

        if ($data->save()) {
            
            // Excel::queueImport(new BookedVoucherDetailImport($data), $request->file('file'));
            Excel::queueImport(new BookedVoucherDetailImport($data),$request->file('file'), \Maatwebsite\Excel\Excel::CSV);
        }
        
        return redirect()->back()->with('success','Data was imported successfully.');
    }

BookedVoucherDetailImport.php

<?php

namespace App\Imports;

use App\Model\BookedVoucher;
use App\Model\BookedVoucherDetail;
use App\Model\Voucher;
// use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\WithChunkReading;
class BookedVoucherDetailImport implements ToCollection, WithStartRow, WithChunkReading, ShouldQueue
{
    /**
     * @var BookedVoucher 
     */
    protected $bookedVoucher;

    /**
     * @param BookedVoucher $bookedVoucher
     */
    public function __construct(BookedVoucher $bookedVoucher)
    {
        $this->bookedVoucher = $bookedVoucher;
    }

    /**
     * @return int
     */
    public function startRow(): int
    {
        return 2;
    }
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */

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

    public function collection(Collection $rows)
    {
        $data = BookedVoucher::latest()->first();
        
        foreach ($rows as $row) 
        {
            $item = new BookedVoucherDetail();
            $item->booked_voucher_id = $this->bookedVoucher->id;
            $item->course_code = $row[0];
            $item->voucher_code = $row[1];
            $item->prakerja_name = $row[2];

            $voucher = Voucher::where('code', $row[1])->first();

            // check the data in the voucher table
            // and set the status in the BookedVoucherDetails table

            if ($voucher && $voucher->claimed == 0 && $voucher->is_booked == 0) {
                $item->status = 'OK';
            } elseif ($voucher && $voucher->claimed == 0 && $voucher->is_booked == 1) {
                $item->status = 'Already Booked';
            } elseif ($voucher && $voucher->claimed == 1 && $voucher->is_booked == 0) {
                $item->status = 'Already Claimed';
            } elseif ($voucher && $voucher->claimed == 1 && $voucher->is_booked == 1) {
                $item->status = 'Already Booked and Claimed';
            } else {
                $item->status = 'Not Found';
            }

            $item->save();

            // check the voucher table.
            // If the data exists, then update is_booked = 1.
            if ($voucher) {
                $voucher->update(['is_booked' => 1]);
            }
        }
    }
}

Blade

<form action="{{ route('booked.import')}}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="form-group">
        <label for="name">Name</label>
        <input name="name" type="text" class="form-control" required>
    </div>
    <div class="form-group">
        <label for="file">File</label>
        <input name="file" type="file" class="form-control" required>
    </div>
    <button type="submit" class="btn btn-primary">Import</button>
</form>

please help, how to import a CSV file with that format?

Hilmi Hidayat
  • 103
  • 4
  • 16
  • have you set the delimiter? https://docs.laravel-excel.com/3.1/imports/custom-csv-settings.html#custom-csv-settings – SuperDJ Sep 21 '21 at 15:11
  • Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – miken32 Sep 21 '21 at 22:44
  • @SuperDJ thx, i've use delimiter and it work. thank you – Hilmi Hidayat Sep 23 '21 at 08:00

3 Answers3

0

The error because of there is no $row[1]. CSV must be separated by commas. Try this in BookedVoucherDetailImport

$item = new BookedVoucherDetail();
$item->booked_voucher_id = $this->bookedVoucher->id;
$item->course_code = expolde(';',$row)[0];
$item->voucher_code = expolde(';',$row)[1];
$item->prakerja_name = expolde(';',$row)[2];

$voucher = Voucher::where('code', expolde(';',$row)[1])->first();
0

For this question, it's solved. i've used delimiter and it work. thank you all

https://docs.laravel-excel.com/3.1/imports/custom-csv-settings.html

Hilmi Hidayat
  • 103
  • 4
  • 16
-1

Import export Excel or CSV from a database is a primary requisite for the admin project. In this tutorial, I will show you how to import CSV or Excel file and export CSV or Excel file utilizing maatwebsite/excel version 3 in Laravel 6 application.

laravelcode.com/post/import-and-export-excel-file-in-laravel-7

bad_coder
  • 11,289
  • 20
  • 44
  • 72