Laravel 12 E-Commerce: Implementing Admin Create New Product
Hi everyone, welcome back to the Laravel E-Commerce Project Tutorial. This video covers the steps for implementing the functionality to add a new product to the admin panel.
1. Controller Function and Route Setup
Fetch Data and Render View (`AdminController.php`)
Create a function to fetch all existing Categories and Brands needed to populate the product form'sdropdowns:
public function add_product()
{
$categories = Category::Select("id","name")->orderBy("name")->get();
$brands = Brand::Select("id","name")->orderBy("name")->get();
return view("admin.product-add",compact("categories","brands"));
}
Define Route for View (`web.php`)
Create the GET route for accessing the new product form:
Route::get("/admin/product/add",[AdminController::class,"add_product"])->name("admin.product.add’);
Create and Setup View (`product-add.blade.php`)
Create the view file, extend the admin layout, and integrate the form content from the template. Update all navigation and dashboard links:
{{ route(‘admin.index’) }}
{{ route(‘admin.products’) }}
2. Update Form for Data and Validation
Form Action and Method (`product-add.blade.php`)
Update the form to use the correct POST action, `enctype` for file uploads, and include the CSRF token:
<form method="POST" action="{{route("admin.product.store")}}" enctype="multipart/form-data" data-parsley-validate>
@csrf
</form>
Populate Dropdowns
Loop through the categories and brands passed from the controller to populate the respective select fields:
<!-- Category Dropdown -->
<select name="category_id" class="form-select" required>
<option value="">Select Category</option>
@foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
<!-- Brand Dropdown -->
<select name="brand_id" class="form-select" required>
<option value="">Select Brand</option>
@foreach($brands as $brand)
<option value="{{$brand->id}}">{{$brand->name}}</option>
@endforeach
</select>
Add Validation and Old Input
For all input fields, add validation error messages and retrieve old input values to maintain form state upon error:
@error("name") <span class="alert alert-danger text-center">{{$message}}</span> @enderror
<input type="text" class="form-control" name="name" placeholder="Enter Product Name" value="{{old("name")}}">
3. Implement Product Store Logic and Route
Store Function (`AdminController.php - product_store`)
Create the function to handle validation, slug generation, main image upload, gallery image upload (comma-separated storage), and database saving:
public function product_store(Request $request)
{
// ... Validation rules (required, unique slug/SKU, prices, etc.) ...
$product = new Product();
$product->name = $request->name;
$product->slug = Str::slug($request->name);
// ... [Assign remaining fields] ...
// Handle Main Image Upload
if ($request->hasFile("image")) {
$image = $request->file("image");
$file_extention = $image->extension();
$file_name = Carbon::now()->timestamp . "." . $file_extention;
$this->GenerateProductThumbnailImage($image, $file_name);
$product->image = $file_name;
}
// Handle Gallery Images Upload (stored as comma-separated string)
$gallery_images = "";
if ($request->hasFile("images")) {
$gallery_arr = [];
$counter = 1;
foreach ($request->file("images") as $gimage) {
$gfile_extention = $gimage->extension();
$gfileName = Carbon::now()->timestamp . $counter . "." . $gfile_extention;
$this->GenerateProductThumbnailImage($gimage, $gfileName);
array_push($gallery_arr, $gfileName);
$counter = $counter + 1;
}
$gallery_images = implode(",", $gallery_arr);
}
$product->images = $gallery_images;
$product->save();
return redirect()->route("admin.products")->with("status", "Product has been added successfully!");
}
Image Helper Function (`GenerateProductThumbnailImage`)
Define the helper to resize and save both the main image and gallery images (for example, saving a large version and a thumbnail):
public function GenerateProductThumbnailImage($image, $imageName)
{
$destinationPathThumbnail = public_path("uploads/products/thumbnails");
$destinationPath = public_path("uploads/products");
$img = Image::read($image->getRealPath());
// Save large image (540x689 cover)
$img->cover(540, 689, "top");
$img->resize(540, 689, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath . "/" . $imageName);
// Save thumbnail (104x104)
$img->resize(104, 104, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPathThumbnail . "/" . $imageName);
}
Define Route for Store (`web.php`)
Define the POST route that the form will submit to:
Route::post("/admin/product/store",[AdminController::class,"product_store"])->name("admin.product.store’);
4. Link Update (`products.blade.php`)
Ensure the main products listing page has the correct link to the creation form:
{{ route(‘admin.product.add’) }}
This completes the process for creating new products in the admin panel.
