CONTROLLER
public function updateproduct(Request $request, $id)
{
if($request->hasfile('images'))
{
foreach($request->file('images') as $file)
{
$name = time().'.'.$file->extension();
if($file->move(public_path().'/files/', $name)){
Image::create([
'images'=>$name,
'product_id'=>$product->id,
]);
}
}
}
$request->validate([
'name'=>'required',
'description'=>'required',
'images'=> 'nullable',
'price'=>'required|numeric',
'quantity'=>'required|numeric',
]);
$product = Product::findOrFail($id);
$product->name=$request->name;
$product->description=$request->description;
$product->price=$request->price;
$product->quantity=$request->quantity;
$product->update();
}
There is products table, images table and product_images table. It works fine while adding new product. But when I update the record, instead of updating data it creates new record.
CodePudding user response:
$product = Product::where('id', $id)->first();
if(is_null($product)) {
$product = new Product();
}
$product->name = $request->input('name');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->quantity = $request->input('quantity');
$product->save();