
PK 
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Category;
use App\Models\Brand;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage; // ADD THIS IMPORT
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$products = Product::getAllProduct();
return view('backend.product.index', compact('products'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
$brands = Brand::get();
$categories = Category::where('is_parent', 1)->get();
return view('backend.product.create', compact('categories', 'brands'));
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|string',
'summary' => 'required|string',
'description' => 'nullable|string',
'photo' => 'required|string',
'size' => 'nullable',
'stock' => 'required|numeric',
'cat_id' => 'required|exists:categories,id',
'brand_id' => 'nullable|exists:brands,id',
'child_cat_id' => 'nullable|exists:categories,id',
'is_featured' => 'sometimes|in:1',
'status' => 'required|in:active,inactive',
'condition' => 'required|in:default,new,hot',
'price' => 'required|numeric',
'discount' => 'nullable|numeric',
'sku' => 'nullable|string|unique:products,sku', // Add validation for SKU
'isGreat_deals' => 'required',
]);
$slug = Str::slug($request->title);
$validatedData['slug'] = $slug;
$validatedData['is_featured'] = $request->input('is_featured', 0);
// Generate SKU if not provided
if (empty($validatedData['sku'])) {
$validatedData['sku'] = $this->generateSku($request->title, $request->cat_id);
}
if ($request->has('size')) {
$validatedData['size'] = implode(',', $request->input('size'));
} else {
$validatedData['size'] = '';
}
$product = Product::create($validatedData);
return redirect()->route('product.index')->with(
$product ? 'success' : 'error',
$product ? 'Product Successfully added' : 'Please try again!!'
);
}
// Add this method to generate SKU
private function generateSku($title, $cat_id)
{
$category = Category::find($cat_id);
$categoryCode = $category ? strtoupper(substr($category->title, 0, 3)) : 'GEN';
$titleCode = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', $title), 0, 3));
$random = strtoupper(Str::random(4));
return $categoryCode . '-' . $titleCode . '-' . $random;
}
/**
* Show the form for editing the specified resource.
*/
public function edit($id)
{
$brands = Brand::get();
$product = Product::findOrFail($id);
$categories = Category::where('is_parent', 1)->get();
$items = Product::where('id', $id)->get();
return view('backend.product.edit', compact('product', 'brands', 'categories', 'items'));
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, $id)
{
$product = Product::findOrFail($id);
$currentPhotos = $product->photo ? explode(',', $product->photo) : [];
$validatedData = $request->validate([
'title' => 'required|string',
'summary' => 'required|string',
'description' => 'nullable|string',
'photo' => 'required|string',
'size' => 'nullable',
'stock' => 'required|numeric',
'cat_id' => 'required|exists:categories,id',
'child_cat_id' => 'nullable|exists:categories,id',
'is_featured' => 'sometimes|in:1',
'brand_id' => 'nullable|exists:brands,id',
'status' => 'required|in:active,inactive',
'condition' => 'required|in:default,new,hot',
'price' => 'required|numeric',
'discount' => 'nullable|numeric',
'sku' => 'nullable|string|unique:products,sku,'.$id, // Add validation for SKU update
'isGreat_deals' => 'required',
]);
// Handle deleted images
$submittedPhotos = $request->photo ? explode(',', $request->photo) : [];
$photosToDelete = array_diff($currentPhotos, $submittedPhotos);
// Delete files from storage
foreach ($photosToDelete as $photo) {
$path = str_replace('/storage/', 'public/', trim($photo));
if (Storage::exists($path)) {
Storage::delete($path);
}
}
$validatedData['is_featured'] = $request->input('is_featured', 0);
if ($request->has('size')) {
$validatedData['size'] = implode(',', $request->input('size'));
} else {
$validatedData['size'] = '';
}
$status = $product->update($validatedData);
return redirect()->route('product.index')->with(
$status ? 'success' : 'error',
$status ? 'Product Successfully updated' : 'Please try again!!'
);
}
/**
* Handle AJAX image deletion
*/
public function deleteImage(Request $request)
{
$request->validate([
'product_id' => 'required|exists:products,id',
'image_path' => 'required|string'
]);
$product = Product::findOrFail($request->product_id);
$currentPhotos = $product->photo ? explode(',', $product->photo) : [];
$updatedPhotos = array_filter($currentPhotos, function($photo) use ($request) {
return trim($photo) !== trim($request->image_path);
});
$product->photo = implode(',', $updatedPhotos);
$product->save();
$path = str_replace('/storage/', 'public/', trim($request->image_path));
if (Storage::exists($path)) {
Storage::delete($path);
}
return response()->json(['success' => true]);
}
/**
* Remove the specified resource from storage.
*/
public function destroy($id)
{
$product = Product::findOrFail($id);
// Delete associated images
if ($product->photo) {
$photos = explode(',', $product->photo);
foreach ($photos as $photo) {
$path = str_replace('/storage/', 'public/', trim($photo));
if (Storage::exists($path)) {
Storage::delete($path);
}
}
}
$status = $product->delete();
return redirect()->route('product.index')->with(
$status ? 'success' : 'error',
$status ? 'Product successfully deleted' : 'Error while deleting product'
);
}
}


PK 99