I want to create a CSV import feature with a CSV format like the image above. With the code I made as below, I always get the error: "Undefined offset: 1" when importing a CSV file.
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]);
}
}
}
}
What is the correct way to import a CSV file with a format like the example above in Laravel?
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