Home > Net >  Add to cart auth
Add to cart auth

Time:02-19

i am trying to make an add to cart button but there is an error that is happening in this line if (Cart::where('prod_id', $product_id)->where('user_id', Auth::id()->exists())) { and the error is: Expected type 'object'. Found 'int|string|null'. it is from the Auth::id in the course that i am taking it is not making any error and it is working fine

class CartController extends Controller
{
    public function addProduct(Request $request)
    {
        $product_id = $request->input('product_id');
        $product_qty = $request->input('product_qty');
        if (Auth::check()) {
            $prod_check = Product::where('id', $product_id)->first();
            if ($prod_check) {
                if (Cart::where('prod_id', $product_id)->where('user_id', Auth::id()->exists())) {
                    return response()->json(['status' => $prod_check->name . ' Already Added to Cart']);
                } else {
                    $cartitem = new Cart();
                    $cartitem->prod_id = $product_id;
                    $cartitem->user_id = Auth::id();
                    $cartitem->prod_qty = $product_qty;
                    $cartitem->save();
                    return response()->json(['status' => $prod_check->name . ' Added to Cart']);
                }
            }
        } else return response()->json(['status' => 'Login to Continue']);
    }
}

CodePudding user response:

You are mixing your parenthesis in ->where('user_id', Auth::id()->exists()) section. exists should be outer side of queryBuilder. You should call ->where('user_id', Auth::id()) after that you should chain ->exists().

if (Cart::where('prod_id', $product_id)->where('user_id', Auth::id())->exists()) {
  • Related