I have product which has many barcodes, when I'm in product edit page and I add/remove/edit barcodes of product it saves barcodes all over again (PS: I am aware where the issue comes from, but not sure about the solution for it)
Logic
So here is what I expect to happen when i'm in product edit page:
- If current barcodes has changed just update them
- if any of current barcodes removed, delete them from database
- if any new barcode added to the list, add it in database
Basically is
sync()functionality that i'm looking for, but based on my model relationships i think usingsync()is not an option.
Code
Product model
public function barcodes()
{
return $this->hasMany(Barcode::class, 'product_id', 'id');
}
barcode model
protected $fillable = [
'product_id', 'serial_number',
];
public function product()
{
return $this->belongsTo(Product::class);
}
Controller (update function)
public function update(Request $request, $id)
{
$product = Product::find($id);
$product->name = $request->input('name');
if($product->save())
{
if(!empty($request->input('barcodes')))
{
foreach($request->input('barcodes') as $bb)
{
if(!empty($bb['serial_number'])){ // make sure no empty value saves
$barcode = new Barcode;
$barcode->product_id = $product->id;
$barcode->serial_number = $bb['serial_number'];
$barcode->save();
}
}
}
}
}
As I mentioned above
I am aware where the issue comes from, but not sure about the solution for itand the issue of duplicate saving data is that I'm using$barcode = new Barcode;.
Extra
In order to be clear, this is what my data looks like when I send update request to back-end
Question
What should I change in my code in order to achieve my desire logic?
