0

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

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

There's the ->exists() method too, which returns true or false based on if any record is found by the Query 🙂 (->count() works just fine too though, but I prefer the explicit true/false return of ->exists())
Thank you @aynber How would I go about updating a record in a database? If the product already exists, I want to increment the quantity by the specified amount in $request. Do i have the right idea with this code: $cart = Cart::where('product_id', $product->id)->where('user_id', $user_id)->update('quantity', /*Get product quantity and increase by $request amount*/);
That's probably where assigning that query to a $cart value would come in. If the cart doesn't exist, create it, and if it does, increment it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.