Part 5: Product Management in Laravel E-Commerce
In this section of the Laravel E-Commerce Tutorial, we’ll focus on building the product management functionality. This includes creating and managing products, uploading product images, and organizing products into categories.
5.1 Creating and Managing Products
Step 1: Create Product Controller
Generate a controller for managing products:
php artisan make:controller ProductController
Define the necessary methods in the ProductController
for creating, updating, and deleting products.
// app/Http/Controllers/ProductController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request; use App\Models\Product; use App\Models\Category;
class ProductController extends Controller { public function index() { $products = Product::all(); return view('products.index', compact('products')); } public function create() { $categories = Category::all(); return view('products.create', compact('categories')); } public function store(Request $request) { // Validation and store logic } public function edit(Product $product) { $categories = Category::all(); return view('products.edit', compact('product', 'categories')); } public function update(Request $request, Product $product) { // Validation and update logic } public function destroy(Product $product) { $product->delete(); return redirect()->route('products.index')->with('success', 'Product deleted successfully.'); } }
Step 2: Create Product Views
Create Blade views for listing, creating, editing, and deleting products. Customize these views based on your application’s design and requirements.
resources/views/products/index.blade.php
: Display a list of products.resources/views/products/create.blade.php
: Form to create a new product.resources/views/products/edit.blade.php
: Form to edit an existing product.
Step 3: Define Product Routes
Define routes for product management in routes/web.php
:
use App\Http\Controllers\ProductController;
Route::resource(‘products’, ProductController::class);
This will create RESTful routes for managing products.
Step 4: Implement Product Views
Implement the product views using Blade templates. Include forms for creating and updating products. Ensure proper validation and error handling in the controller.
5.2 Uploading Product Images
Step 1: Update Products Table
Add a column for storing the product image path in the products table:
php artisan make:migration add_image_to_products_table --table=products
Edit the migration file:
// database/migrations/YYYY_MM_DD_add_image_to_products_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddImageToProductsTable extends Migration { public function up() { Schema::table(‘products’, function (Blueprint $table) { $table->string(‘image’)->nullable(); }); } public function down() { Schema::table(‘products’, function (Blueprint $table) { $table->dropColumn(‘image’); }); } }
Run the migration:
php artisan migrate
Step 2: Update ProductController
Update the store and update methods in the ProductController to handle image uploads:
// app/Http/Controllers/ProductController.php
use Illuminate\Support\Facades\Storage;
class ProductController extends Controller { public function store(Request $request) { $request->validate([ 'image' => 'image|mimes:jpeg,png,jpg,gif|max:2048', ]); $product = new Product($request->all()); if ($request->hasFile('image')) { $imagePath = $request->file('image')->store('products', 'public'); $product->image = $imagePath; } $product->save(); return redirect()->route('products.index')->with('success', 'Product created successfully.'); } public function update(Request $request, Product $product) { $request->validate([ 'image' => 'image|mimes:jpeg,png,jpg,gif|max:2048', ]); $product->update($request->all()); if ($request->hasFile('image')) { // Delete old image if it exists if ($product->image) { Storage::disk('public')->delete($product->image); } $imagePath = $request->file('image')->store('products', 'public'); $product->image = $imagePath; $product->save(); } return redirect()->route('products.index')->with('success', 'Product updated successfully.'); } }
Step 3: Display Product Images in Views
Update the product views to display product images:
{{-- resources/views/products/index.blade.php --}}
@foreach ($products as $product)
<img src="{{ asset('storage/' . $product->image) }}" alt="{{ $product->name }}" width="100">
{{-- Other product details --}}
@endforeach {{-- resources/views/products/create.blade.php --}}
<form action="{{ route('products.store') }}" method="post" enctype="multipart/form-data">
@csrf
{{-- Existing form fields --}}
<input type="file" name="image">
{{-- Submit button --}}
</form> {{-- resources/views/products/edit.blade.php --}}
<form action="{{ route('products.update', $product->id) }}" method="post" enctype="multipart/form-data">
@csrf
@method('PUT')
{{-- Existing form fields --}}
<input type="file" name="image">
{{-- Submit button --}}
</form>
5.3 Adding Product Categories and Tags
Step 1: Create Categories Table
If you haven’t already created the categories table, follow the steps from Part 3 to create it.
Step 2: Update Products Table
Add a foreign key for the category_id in the products table. Run the migration:
php artisan make:migration add_category_id_to_products_table --table=products
Edit the migration file:
// database/migrations/YYYY_MM_DD_add_category_id_to_products_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddCategoryIdToProductsTable extends Migration {
public function up() {
Schema::table('products', function (Blueprint $table) {
$table->unsignedBigInteger('category_id')->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('set null'); });
}
public function down() {
Schema::table('products', function (Blueprint $table) {
$table->dropForeign(['category_id']); $table->dropColumn('category_id');
});
} }
Run the migration:
php artisan migrate
Step 3: Update Product Views
Update the product views to include the category dropdown:
{{-- resources/views/products/index.blade.php --}}
@foreach ($products as $product){{-- resources/views/products/index.blade.php --}}
<p>Category: {{ $product->category->name }}</p>
{{-- Other product details --}}
@endforeach{{-- resources/views/products/create.blade.php --}}
<form action="{{ route('products.store') }}" method="post" enctype="multipart/form-data">
@csrf
{{-- Existing form fields --}}
<label for="category">Category:</label>
<select name="category_id" id="category">
@foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
@endforeach
</select>
<input type="file" name="image">
{{-- Submit button --}}
</form>{{-- resources/views/products/edit.blade.php --}}
<form action="{{ route('products.update', $product->id) }}" method="post" enctype="multipart/form-data">
@csrf
@method('PUT')
{{-- Existing form fields --}}
<label for="category">Category:</label>
<select name="category_id" id="category">
@foreach ($categories as $category)
<option value="{{ $category->id }}" @if($product->category_id == $category->id) selected @endif>{{ $category->name }}</option>
@endforeach
</select>
<input type="file" name="image">
{{-- Submit button --}}
</form>
5.4 Summary
Congratulations! You’ve implemented product management functionality in your Laravel E-Commerce application. Users can now create, update, and delete products, upload product images, and assign products to categories. In the next part of the tutorial, we’ll focus on implementing the shopping cart functionality. Stay tuned for the next steps!