Viewing file: ProductController.php (14.37 KB) -rw-r--r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Models\Category; use App\Models\CategoryDescription; use App\Models\Customer; use App\Models\Manufacturer; use App\Models\Product; use App\Models\ProductDescription; use App\Models\ProductImage; use App\Models\ProductRelated; use App\Models\ProductRelatedAttribute; use App\Models\ProductSpecial; use App\Models\Setting; use App\Models\StoreProductOption; use App\Traits\CustomFileTrait; use GuzzleHttp\Client; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Route; use Illuminate\Support\Str;
class ProductController extends Controller {
use CustomFileTrait;
public function __construct() { $this->path = public_path(config('constant.file_path.product')); $this->customDateFormat = config('constant.date_format')['custom_date_format']; $this->databaseDateFormat = config('constant.date_format')['database_date_format']; }
public function store(Request $request) {
DB::beginTransaction();
try { $this->validateData($request);
$product = new Product($request->only('model', 'sku', 'quantity', 'price', 'category_id'));
$product->stock_status_id = $request->stock_status_id ? $request->stock_status_id : 0; $product->manufacturer_id = $request->manufacturer_id ? $request->manufacturer_id : 0; $product->tax_rate_id = $request->tax_rate_id ? $request->tax_rate_id : 0; if ($request->date_available) { $product->date_available = $request->date_available; } else { $product->date_available = date('d/m/Y'); }
$product->length = $request->length ? $request->length : 0; $product->width = $request->width ? $request->width : 0; $product->height = $request->height ? $request->height : 0; $product->weight_class_id = $request->weight_class_id ? $request->weight_class_id : 0; $product->weight = $request->weight ? $request->weight : 0; $product->status = 1; $product->sort_order = $request->sort_order ? $request->sort_order : 0; $product->save();
$description = new ProductDescription(); $buildMultiLanguage = $description->buildMultiLang($product->id, $request->multilanguage); $description->upsert($buildMultiLanguage, ['product_id', 'short_description', 'description', 'language_id', 'name', 'meta_title', 'meta_description', 'meta_keyword']);
// Save Attributes $attributesArray = $this->getAttributeProductData($product->id, $request->attributesArray); if (count($attributesArray) > 0) { ProductRelatedAttribute::insert($attributesArray); }
// Save Related Product $relatedProducts = $this->getRelatedProductData($product->id, $request->related_id); ProductRelated::insert($relatedProducts);
// Save Product Special if ($request->special_price != null) { $specialProduct = [ 'product_id' => $product->id, 'price' => $request->special_price, 'start_date' => $this->changeDateFormat($request->start_date, $this->customDateFormat, $this->databaseDateFormat), 'end_date' => $this->changeDateFormat($request->end_date, $this->customDateFormat, $this->databaseDateFormat) ]; ProductSpecial::insert($specialProduct); }
//save Options $optionArr = []; if ($request->optionPost) { $postOptions = explode(',', $request->optionPost); foreach ($postOptions as $key => $value) { for ($i = 0; $i < count($request->option[$value]['label']); $i++) { if ($request->option[$value]['label'][$i] != null) { $optionArr [] = [ 'label' => $request->option[$value]['label'][$i], 'price' => $request->option[$value]['price'][$i], 'color_code' => array_key_exists('color_code', $request->option[$value]) ? $request->option[$value]['color_code'][$i] : '', 'option_id' => $value, 'product_id' => $product->id ]; } } } }
if (count($optionArr) > 0) { StoreProductOption::insert($optionArr); }
DB::commit(); cache()->forget('newProducts'); cache()->forget('trendingProducts'); cache()->forget('topBrands');
return response()->json(['message' => 'Product successfully created', 'status' => 'success']); } catch (\Exception $ex) { DB::rollBack(); Log::info($ex); return response()->json(['message' => $ex->getMessage(), 'status' => 'failed']); } }
public function update(Request $request,$id) {
DB::beginTransaction();
try { $this->validateData($request);
$product = Product::whereId($id)->first();
if(!$product){ return response()->json(['status'=>'failed', 'message'=>'Invalid Product']); }
if ($request->hasFile('main_image')) { $this->removeOldImage($product->image, $this->path); $product->image = $this->saveCustomFileAndGetImageName(request()->file('main_image'), $this->path); }
$product->fill($request->only(Product::$fillableValue))->save();
$product->productRelated()->delete();
// Save Related Product $relatedProducts = $this->getRelatedProductData($product->id, $request->related_id); ProductRelated::insert($relatedProducts);
// Save Attributes ProductRelatedAttribute::deleteByProduct($id);
$attributesArray = $this->getAttributeProductData($product->id, $request->attributesArray); if (count($attributesArray) > 0) { ProductRelatedAttribute::insert($attributesArray); }
$description = new ProductDescription(); $description->where('product_id', $id)->delete(); $buildMultiLanguage = $description->buildMultiLang($product->id, $request->multilanguage); $description->upsert($buildMultiLanguage, ['product_id', 'short_description', 'description', 'language_id', 'name', 'meta_title', 'meta_description', 'meta_keyword']);
//update Options StoreProductOption::where('product_id', $id)->delete(); $optionArr = []; if ($request->optionPost) { $postOptions = explode(',', $request->optionPost);
foreach ($postOptions as $key => $value) { for ($i = 0; $i < count($request->option[$value]['label']); $i++) { if ($request->option[$value]['label'][$i] != null) { $optionArr [] = [ 'label' => $request->option[$value]['label'][$i], 'price' => $request->option[$value]['price'][$i], 'color_code' => array_key_exists('color_code', $request->option[$value]) ? $request->option[$value]['color_code'][$i] : '', 'option_id' => $value, 'product_id' => $product->id ]; } } } }
if (count($optionArr) > 0) { StoreProductOption::insert($optionArr); }
//image update $oldImagesData = ProductImage::where('product_id', $id)->get(); $oldImageIds = $oldImagesData->pluck('id')->toArray(); $productImageIds = []; $newImageArray = []; if (isset($request->product_image['sort_order_image']) && $request->product_image['sort_order_image']) { foreach ($request->product_image['sort_order_image'] as $key => $value) { if (isset($request->product_image['id'][$key])) { $imageId = $request->product_image['id'][$key]; $productImageIds[] = $imageId; $productImage = ProductImage::whereId($imageId)->first(); if (isset($request->product_image['image'][$key])) { $image = $request->product_image['image'][$key]; $this->removeOldImage($productImage->image, $this->path); $productImage->image = $this->saveCustomFileAndGetImageName($image, $this->path); } $productImage->sort_order_image = $request->product_image['sort_order_image'][$key]; $productImage->save(); } else { if (array_key_exists('image', $request->product_image)) { $image = $request->product_image['image'][$key]; $imageName = $this->saveCustomFileAndGetImageName($image, $this->path); $newImageArray[] = [ 'product_id' => $id, 'sort_order_image' => $request->product_image['sort_order_image'][$key], 'image' => $imageName ]; }
} } }
$deletedImageIds = array_diff($oldImageIds, $productImageIds); $oldProductImages = $oldImagesData->pluck('image', 'id')->toArray();
ProductImage::whereIn('id', $deletedImageIds)->delete(); ProductImage::insert($newImageArray);
// Remove deleted Images foreach ($deletedImageIds as $key => $value) { $this->removeOldImage($oldProductImages[$value], $this->path); }
if ($request->special_price != null) { ProductSpecial::where('product_id', $id)->delete(); $newSpecialArray[] = [ 'product_id' => $id, 'price' => $request->special_price, 'start_date' => $this->changeDateFormat($request->start_date, $this->customDateFormat, $this->databaseDateFormat), 'end_date' => $this->changeDateFormat($request->end_date, $this->customDateFormat, $this->databaseDateFormat) ];
ProductSpecial::insert($newSpecialArray);
}
DB::commit();
cache()->forget('newProducts'); cache()->forget('trendingProducts'); cache()->forget('topBrands');
cache()->flush();
return response()->json(['status'=>'success', 'message'=>'Product Successfully Updated']); }catch(\Exception $ex){ DB::rollBack(); Log::info($ex); return response()->json(['status'=>'failed', 'message'=>$ex->getMessage()]); } }
public function delete($id) { DB::beginTransaction();
try { $data=Product::where('id', $id)->first();
if(! $data) { return response()->json(['message'=>'Product Not Found', 'status'=>'failed']); }
$this->removeOldImage($data->image,$this->path); $images = $data->images()->pluck('image'); if(count($images) > 0){ foreach($images as $key => $value) { $this->removeOldImage($value,$this->path); } }
$data->productRelated()->delete(); $data->special()->delete(); $data->images()->delete(); $data->productDescription()->delete(); $data->delete();
cache()->forget('newProducts'); cache()->forget('trendingProducts'); cache()->forget('topBrands'); cache()->flush();
DB::commit(); return response()->json(['status'=>'success', 'message'=>'Product Successfully Deleted']); }catch(\Exception $ex){ DB::rollBack(); return response()->json(['status'=>'failed', 'message'=>$ex->getMessage()]); } }
protected function getRelatedProductData($productId,$relatedIds) { $dataArray = []; if(isset($relatedIds)) { foreach($relatedIds as $key => $value) { $dataArray[] = [ 'product_id' => $productId, 'related_id' => $value ]; } } return $dataArray; }
protected function getAttributeProductData($productId,$attributesArray) { $dataArray = [];
if($attributesArray) { foreach ($attributesArray as $key => $value) { if ($value['text'] != null) { $dataArray[] = [ 'product_id' => $productId, 'attribute_id' => $value['attribute_id'] ?? 2, 'text' => $value['text'], ]; } } } return $dataArray; }
protected function getproductImages($productId,$productImages) { $dataArray = [];
foreach($productImages['sort_order_image'] as $key => $value) { $image = $this->saveCustomFileAndGetImageName($productImages['image'][$key],$this->path); $dataArray[] = [ 'product_id' => $productId, 'sort_order_image' => $value, 'image' => $image ]; } return $dataArray; }
protected function validateData ($request) {
$conditionArray = [];
$validateFields = [ 'multilanguage.*.name' => ['required'], 'category_id' => ['required'], 'model' => ['required'], 'quantity' => ['required'], 'price' => ['required'], ];
$validationArray = array_merge($conditionArray,$validateFields); $this->validate($request,$validationArray); }
}
|