I'm using Laravel Excel by https://laravel-excel.com/. I have a CSV file that has data like:
I want to import some CSV and validate the existed data and not inserting it into database.
But, I want to insert data that not existed in database and I don't know how to validate it.
I just want to insert the new data together and denying the old one for the purpose of preventing some duplicate data after importing CSV into a database and reducing human error.
I have example code like this:
<?php
namespace App\Imports\Points;
use App\Models\PointRegular;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\Importable;
class PointsRegularImport implements ToCollection, WithHeadingRow
{
use Importable;
public function collection(Collection $rows)
{
foreach($rows as $row) {
// Check existing data in database
$pointRegulars = PointRegular::orderBy('created_at', 'desc')
->where('product_id', $row['product_id'])
->where('channel_id', $row['channel_id'])
->where('transaction_type_id', $row['transaction_type_id'])
->where('payment_method_id', $row['payment_method_id'])
->get();
foreach($pointRegulars as $pointRegular) {
// Check for update data with id
if($row->has('id')) {
if($pointRegular->id == $row['id']) {
$point = PointRegular::findOrFail($row['id']);
$point->product_id = $row['product_id'];
$point->channel_id = $row['channel_id'];
$point->transaction_type_id = $row['transaction_type_id'];
$point->payment_method_id = $row['payment_method_id'];
}
} else {
// Create new data
// Check for data existed in database
// If exist, deny existed data and insert new data
if($pointRegular) {
return "Existed and not insert";
} else {
return "You Inserting new data without creating the old one";
}
}
}
}
}
}