У меня есть таблица продуктов, и пользователь может добавлять продукты в корзину, выбрав несколько продуктов с помощью флажка. Проблема связана с синхронизацией отношения «Один ко многим» c.
Модель моей тележки:
protected $fillable = [
'currency',
'price',
'user_id',
];
//Table Names
protected $table = 'carts';
public function product()
{
return $this->belongsToMany(Product::class);
}
Модель моих продуктов:
public function carts()
{
return $this->hasMany(Cart::class);
}
My cart_products datatable
cart_id and product_id
Когда я сохраняю несколько продуктов в корзину, они добавляются и синхронизируются c только с последним идентификатором корзины. Все product_id верны.
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');
}
Мне нужна помощь в понимании того, как правильно синхронизировать c cart_id.