On the checkout page, I create an order and write the data from the basket to it, write it in a loop
foreach($items_cart as $item) {
    //write related data to staging table
    $order->product() ->attach([$item['item_id']=>['product_quantity'=>$item['quantity'],'product_color'=> $item['color']]]);
}


But let's say the user decided to return to put something else in the basket, and delete something.So when I return to the checkout page, I need to make changes — remove what is no longer in the basket and add a new one.And if there are no changes, leave it as Is there.Can it be done and how?

2 Answers 2

There are 2 ways, simple and dreary.
The simple way is to delete old data from the recycle bin each time and write new ones.
The dreary way is a combination of the array_diff functions to find out which products need to be added and which ones to delete
$attached=array_diff($new, $old);
 $deleted=array_diff($old, $new);
Laravel has an excellent sync method.I recommend carefully reviewing the documentation before asking such questions.

Search(ctrl + f) by sync(
  • [[be_a_dancer]] justice for the sake of sync only works for ManyToMany.and there will probably be OneToMany here – Nervous93 May 22 '19 at 18:51
  • [[dk-web]], even if there are many to many, I have attributes that are written in the intermediate table, so the product id is repeated, this makes it difficult to use sync – Dizzy100 May 22 '19 at 19:34
  • [[semki096]], https://github.com/Crinsane/LaravelShoppingcart
    I tried to use such a disaster.
    – Nervous93 May 22 '19 at 19:48