Home > Software engineering >  How to use a SQL statement in controller laravel using AND clause
How to use a SQL statement in controller laravel using AND clause

Time:11-29

This is my piece of code

 $user_id = Auth::id();
        if(Cart::where('product_id', $product->id and 'user_id', $user_id) === null)
        {
            $cart = new Cart;
            $cart->product_id = $product->id;
            $cart->quantity = $request->get('quantity');
            $cart->user()->associate(Auth::user());
            $cart->save();
        }
        else
        {
    
        }

This code I know definitely works

$cart = new Cart;
$cart->product_id = $product->id;
$cart->quantity = $request->get('quantity');
$cart->user()->associate(Auth::user());
$cart->save();

The issue is somewhere in the if statement but I'm not sure what it is. I am trying to check the carts table in the database to see if there is a cart that already exists with the same product id and user ID. If it isn't, it creates a cart in the database. Here is my database table:

enter image description here

CodePudding user response:

You need to break up your syntax into separate clauses.

Cart::where('product_id', $product->id)->where('user_id', $user_id)->first()

You can use ->first() to grab the first record, which is useful if you actually want to assign the value to a variable to use. Or you can use ->count() if you don't need to grab the record, and check to see if the count is equal to 0.

  • Related