6

I have a Cart model like this :

class Cart extends Model
    {
        protected $table = 'cart';

        protected $fillable = ['user_id', 'delivery_method'];

        public function products ()
        {
            return $this->belongsToMany(Product::class, 'cart_products', 'cart_id', 'product_id')->withPivot('quantity');
        }

    }

And cart table columns are :

id
user_id
delivery_method
created_at
updated_at

And there is a pivot table named cart_products to relate Card model to a Product Model.

Suppose I have an specific $user_id variable. now I want Cart with that user_id with their products. for that I wrote this :

$cartWithProducts = Cart::with('products')->where(['user_id' => $user_id])->first();

if (!$cartWithProducts->isEmpty()) {
//Some codes come here
}

But after run, I got this error :

Call to undefined method Illuminate\Database\Query\Builder::isEmpty() {"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method Illuminate\\Database\\Query\\Builder::isEmpty() at D:\\wamp\\www\\barlly\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php:2461

I do not want to use lazy loading approach beacause n query problem. what is solution in this case?

Also each User can have only one Cart in time.

1
  • 1
    When you call first(), it returns a single object or null. So, you are trying to call isEmpty(), which is a Collection method, on a single object. Commented Jan 26, 2018 at 18:31

3 Answers 3

14

you can just call

if ($cartWithProducts) {
//Some codes come here
}

Have a read over this Answer

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

4 Comments

I tired that, But if block does not run while I have a Card this that conditions in database.
Oops, I forgot to remove !
use ->get() instead of ->first() in your query
But in this case it return an array of cart, right?. but I only save one cart for each user_id and now I want to select that one only
3

Expecting your can have multiple carts for specified users and you may proceed more than one I would recommend to do something like this:

$cartWithProducts = Cart::whereUserId($user_id)->with('products')->get();

if ($cartWithProducts->isNotEmpty()) {
    //Some codes come here
}

Comments

2

first() returns null if there is no Cart for the user, so if you want to check if it's empty, you can use is_null() or empty() instead of if (!$cartWithProducts) to keep is readable:

if (is_null($cartWithProducts))

Comments

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.