- Now Let's finish our Controller code, at first navigate app/Http/Controllers/Productcontroller and write index() method:
public function index()
{
//fetching all the products from the database via model
$products = Product::all();
//pass all the data in the view
return view('products.index', compact('products'));
}
- Now we will write our create() method code:
public function create()
{
return view('products.create');
}
- Now we can make our store() method functional write this:
public function store(Request $request)
{
// validate the request data
$request->validate([
'name' => 'required',
'description' => 'required',
'price' => 'required',
'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
// assigning filepath of the storage
$imagePath = null;
if ($request->hasFile('image')) {
$imagePath = $request->file('image')->store('images', 'public');
}
Product::create([
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
'image' => $imagePath,
]);
// redirecting to the index page
return redirect()->route('products.index')->with('success', 'Product created successfully.');
}
- Now we will write our show() method code to show soecific selected product in the controller write this:
public function show(Product $product)
{
return view('products.show', compact('product'));
}
- In your Product controller edit() method paste this to redirect your edit form:
public function edit(Product $product)
{
return view('products.edit', compact('product'));
}
- find the update() method and paste this code:
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'required',
'description' => 'required',
'price' => 'required',
'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$imagePath = $product->image;
if ($request->hasFile('image')) {
if ($imagePath) {
// Delete the old image
Storage::disk('public')->delete($imagePath);
}
$imagePath = $request->file('image')->store('images', 'public');
}
$product->update([
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
'image' => $imagePath,
]);
return redirect()->route('products.index')->with('success', 'Product updated successfully.');
}
- It's almost finished with controller just paste this code in your destroy() method to complete the controller:
public function destroy(Product $product)
{
if ($product->image) {
Storage::disk('public')->delete($product->image);
}
$product->delete();
return redirect()->route('products.index')->with('success', 'Product deleted successfully.');
}