php - Laravel 7.14 Sync/attach cart_id to product_id One to Many relation

I have a products table and user can add products to cart by selecting multiple products with checkbox. The problem is with One to Many relation sync.

My Cart Model:

protected $fillable = [
    'currency',
    'price',
    'user_id',
];

//Table Names
protected $table = 'carts';

public function product()
{
    return $this->belongsToMany(Product::class);
}

My Products Model:

public function carts()
{
    return $this->hasMany(Cart::class);
}

My cart_products datatable

cart_id and product_id

When ever I save multiple products to cart, it get's added and gets sync with last cart_id only. All product_id is correct.

My CartController:

public function store(Request $request)
{

    $this->validate($request, [
        'product_id' => 'required',
        'currency' => '',
        'price' => '',
    ]);

    $user = Auth::user()->id;

    $product_id = $request->product_id;

    // dd($product_id);

    foreach($product_id as $cart) {
        // dd($cart[0]);
        $cart = Cart::create([
            'currency' => $request['currency'],
            'price' => $request['price'],
            'user_id' => $user,
        ]);
    }
    
    $cart->product()->sync($product_id);

    return redirect()->back()->with('toast_success', 'Item(s) added in cart');
}

I need help understanding how to properly sync cart_id as well.

Answer

Solution:

no wonder it's because sync the products relation is outside the loop that why it only set for last cart. move the sync into loop like this:

    foreach($product_id as $cart) {
        $cart = Cart::create([
            'currency' => $request['currency'],
            'price' => $request['price'],
            'user_id' => $user,
        ]);
    $cart->product()->sync($product_id);
    }
    

Source