Viewing File: /home/ubuntu/vedadeals-backend-base/app/Imports/ProductsImport.php
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use App\Models\{ Product, Category, SubCategory, ProductFile };
use App\Helpers\Helper;
use Illuminate\Support\Str;
use DB, Exception;
class ProductsImport implements ToCollection
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function collection(Collection $rows)
{
try {
DB::beginTransaction();
foreach($rows as $row) {
$category = Category::firstWhere(['name' => $row[3]]);
$sub_category = SubCategory::firstWhere(['name' => $row[4]]);
$is_exists = Product::where(['id' => $row[0]])->exists();
if($is_exists) {
throw new Exception("Product Already Exits. Product ID : $row[0]");
}
$product = Product::create([
'id' => $row[0],
'name' => $row[1],
'description' => $row[2],
'category_id' => $category->id ?? 0,
'sub_category_id' => $sub_category->id ?? 0,
'original_price' => $row[5],
'price' => $row[6],
'quantity' => $row[7],
'gross_weight' => $row[8],
'unit' => $row[9],
'thc_from' => $row[10],
'thc_to' => $row[11],
'cbd_from' => $row[12],
'cbd_to' => $row[13],
'plant_type' => $row[14],
'status' => DECLINED
]);
$file_url = asset(IMPORT_PRODUCT_FILE_PATH)."/$product->id.png";
$result = $product->update(['file' => $file_url]);
$product_file = ProductFile::Create(['product_id' => $product->id, 'file' => $file_url, 'file_type' => IMAGE]);
if(!$product && !$product_file && !$result) {
throw new Exception(api_error(144), 144);
}
}
DB::commit();
return redirect()->route('admin.products.index')->with('flash_success', tr('products_exported_success'));
} catch(Exception $e) {
DB::rollback();
info($e->getMessage());
return redirect()->back()->with('flash_error' , $e->getMessage());
}
}
}
Back to Directory
File Manager