I am working with Laravel Excel Imports https://docs.laravel-excel.com/3.1/imports/
With the help of this, i have written AccessoryImport.php
I want to import my csv file which takes three input - vendor name, barcode and description..
Vendor name is being stored in vendor table and cooresponding id is being stored in accessory table.
But if vendor already exists, just fetch that id instead of creating new vendor in vendor table.
I have applied condition and all but still duplicate entries are being made in my database.
<?php
namespace App\Imports;
use App\Accessory;
use App\AccessoryVendor;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class AccessoryImport implements ToCollection, WithHeadingRow
{
public function collection(Collection $rows)
{
foreach($rows as $row)
{
$vendor = AccessoryVendor::where('name', '=', $row['vendor'])->get();
//return $vendor;
if($vendor === null) {
$newvendor = AccessoryVendor::create([
'name' => $row['vendor'],
]);
Accessory::create([
'vendor_id' => $newvendor->id,
'description' => $row['description'],
'barcode' => $row['barcode'],
]);
}
else
{
Accessory::create([
'vendor_id' => $vendor->id,
'description' => $row['description'],
'barcode' => $row['barcode'],
]);
}
}
}
}
CodePudding user response:
You could just use the firstOrCreate() Eloquent method - it will find the model if it exists, and create it if not, returning it either way.
CodePudding user response:
Perhaps you can do it like this:
$checkIfVendorExists = AccessoryVendor::where('name', '=', $row['vendor'])->first();
if ($checkIfVendorExists !== null) {
Accessory::create([
'vendor_id' => $checkIfVendorExists->id,
'description' => $row['description'],
'barcode' => $row['barcode'],
]);
}
If vendor names are unique, then you should use ->first()
instead of ->get()
when trying to check for existing records.