在 Laravel 中,在更新产品记录时,它会创建新记录

In Laravel, While updating Product record, it creates new record

控制器

   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();
}

有产品 table、图像 table 和 product_images table。添加新产品时效果很好。但是当我更新记录时,它没有更新数据而是创建了新记录。

$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();