I am new to Laravel, here my existing fields are getting updated but unable to insert a new row, when users checks for a new category it should be added as a new row in the database.
public function update(Request $request, $id) { $this->validate($request, [ 'name' => 'required', 'shop_id' => 'required', 'sub_category_id' => 'sometimes|required|', 'is_visible' => 'required', 'is_active' => 'required', ]); try { $product = Product::find($id); $product->name = $request->name; $product->shop_id = $request->shop_id; $product->is_visible = $request->is_visible; $product->is_active = $request->is_active; $product->save(); foreach($request->category_id as $key =>$v){ $data = array( 'product_id'=>$id, 'category_id'=> $v, 'sub_category_id'=>isset($request->sub_category_id [$key])?$request->sub_category_id [$key]:null, 'total_quantity'=>$request->total_quantity [$key], 'quantity_unit'=>$request->quantity_unit [$key] ); $ewast = EwasteItem::where('product_id','=',$id)->where('category_id','=',$request->category_id [$key])->get(); if ($ewast) { $ewasteitem = EwasteItem::where('product_id',$id)->where('category_id',$v); $ewasteitem->update($data); } else { EwasteItem::insert($data); } } return Redirect::route('ewaste.index')->with('successMessage', 'Product Updated Successfully.'); } catch (ModelNotFoundException $e) { return $e; } }
Advertisement
Answer
Update the foreach loop as follow
foreach($request->category_id as $key =>$v) { $data = array( 'product_id'=>$id, 'category_id'=> $v, 'sub_category_id'=>isset($request->sub_category_id [$key])?$request->sub_category_id [$key]:null, 'total_quantity'=>$request->total_quantity [$key], 'quantity_unit'=>$request->quantity_unit [$key] ); $ewasteitem = AppEwasteItem::updateOrCreate( ['product_id' => $id, 'category_id' => $v], $data ); }
also, check that in your AppEwasteItem model have $fillable array and it has the element ‘product_id’
protected $fillable = ['product_id', ...other_column_names];