public function add_to_cart(Request $request)
{
// session()->forget('cart');
try{
if(session()->has('cart.session_id')) //cart update code
{
if(!session()->has('user.id'))//if user not logged in
{
$prev_rec = ShoppingCart::where(['cart_session_id' => session()->get('cart.session_id'), 'product_id' => $request->product_id])->first();
if($prev_rec != null)//if product existed in session id, shopping cart, upgrading the cart value
{
$res = $prev_rec->update([
'product_id' => $request->product_id,
'price' => $request->price,
'net_price' => $prev_rec->net_price + ($request->order_qty * $request->price),
'quantity' => $prev_rec->quantity + $request->order_qty,
'discount' => null,
'status' => 'A',
]);
}
else //if adding a new product which wasn't in session id, shopping cart
{
$res = ShoppingCart::create([
'cart_session_id' => session()->get('cart.session_id'),
'product_id' => $request->product_id,
'price' => $request->price,
'net_price' => $request->order_qty * $request->price,
'quantity' => $request->order_qty,
'discount' => null,
'status' => 'A',
]);
}
}
elseif(session()->has('user.id'))//if user logged in
{
$prev_rec = ShoppingCart::where(['user_id' => session()->get('user.id'), 'product_id' => $request->product_id])->first();
if($prev_rec != null)
{
$res = $prev_rec->update([
'product_id' => $request->product_id,
'price' => $request->price,
'net_price' => $request->order_qty * $request->price,
'quantity' => $request->order_qty,
'discount' => null,
'status' => 'A',
]);
}
else
{
$res = ShoppingCart::create([
'user_id' => session()->get('user.id'),
'cart_session_id' => session()->get('cart.session_id'),
'product_id' => $request->product_id,
'price' => $request->price,
'net_price' => $request->order_qty * $request->price,
'quantity' => $request->order_qty,
'discount' => null,
'status' => 'A',
]);
}
}
return response()->json([
'status'=>'Cart updated',
], 200);
}
elseif(!session()->has('cart.session_id')) //creating new cart
{
$cart_id = $this->generate_cart_id();
session()->put([
'cart.session_id' => $cart_id,
]);
if(!session()->has('user.id')) //if user not logged in
{
$res = ShoppingCart::create([
'cart_session_id' => $cart_id,
'product_id' => $request->product_id,
'price' => $request->price,
'net_price' => $request->order_qty * $request->price,
'quantity' => $request->order_qty,
'discount' => null,
'status' => 'A',
]);
}
elseif(session()->has('user.id')) //if user logged in
{
$res = ShoppingCart::create([
'user_id' => session()->get('user.id'),
'cart_session_id' => $cart_id,
'product_id' => $request->product_id,
'price' => $request->price,
'net_price' => $request->order_qty * $request->price,
'quantity' => $request->order_qty,
'discount' => null,
'status' => 'A',
]);
}
return response()->json([
'status'=>'Cart created',
], 200);
}
}
catch(Exception $e1)
{
return response()->json([
'status' => $e1->getMessage(),
], 400);
}
}