Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to undefined method Illuminate\Database\Query\Builder::isEmpty on eager loading laravel

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.

like image 709
A.B.Developer Avatar asked Jan 26 '18 18:01

A.B.Developer


2 Answers

you can just call

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

Have a read over this Answer

like image 115
ATechGuy Avatar answered Oct 26 '22 04:10

ATechGuy


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
}
like image 3
patriziotomato Avatar answered Oct 26 '22 03:10

patriziotomato