Laravelshoppingcart: Problem when associating with model

Created on 30 Jun 2016  Â·  8Comments  Â·  Source: Crinsane/LaravelShoppingcart

i tried

Cart::associate('Product')->add('293ad', 'Product 1', 1, 9.99, array('size' => 'large'));
here error: Missing argument 2 for Gloudemans\Shoppingcart\Cart::associate()
though documentation said second argument is optional

Cart::associate('Product','App\Models')->add('293ad', 'Product 1', 1, 9.99, array('size' => 'large'));
and
Cart::associate('App\Models','Product')->add('293ad', 'Product 1', 1, 9.99, array('size' => 'large'));
and
here error: The supplied model App\Models does not exist.

Cart::associate('App\Models\Product','App\Models\Product')->add('293ad', 'Product 1', 1, 9.99, array('size' => 'large'));

here error: cart does not contain rowId App\Models\Product

I tried to follow the documentation but no luck

please help

Most helpful comment

thank you guys. [ Crinsane, djaca]
$x->model->name; solved the null object error.

All 8 comments

Try Cart::add('293ad', 'Product 1', 1, 9.99, array('size' => 'large'))->associate('Product','App\Models');

Thanks for the reply.
I tried what you've suggested in the following code
Cart::instance('cart')->add('15', 'Product 1', 1, 9.99, array('size' => 'large'))->associate('Product','App\Models');

     $cart =  Cart::instance('cart');
     // dd($cart->content());
     foreach($cart->content() as $x){
        echo $x->product->name;
     }

I get the following error

Trying to get property of non-object

  $cartItem = Cart::add('17', 'Product1', 1, 10.00);
    Cart::associate($cartItem->rowId, \App\Models\Product::class);

     foreach(Cart::content() as $x){
        echo $x->product->name;
     }

still getting: Trying to get property of non-object

when i dump the cart i get

Collection {#282 â–¼
#items: array:2 [â–¼
"693a016600c28ef6002d156c729881ea" => CartItem {#283 â–¼
+rowId: "693a016600c28ef6002d156c729881ea"
+id: "15"
+qty: 8
+name: "Product 1"
+price: 9.99
+options: CartItemOptions {#284 â–¶}
-associatedModel: "App\Models\Product"
-taxRate: 21
}
"a4e935a75812667a849f3dfef1c5940b" => CartItem {#307 â–¶}
]
}

Thanx

what is wrong with my code. or there is other ways to access the associated model other than what I did on the foreach loop?

Instead echo $x->product->name; try echo $x->model->name;

thank you guys. [ Crinsane, djaca]
$x->model->name; solved the null object error.

Instead of using the model name version 2 now allows you to access the model and its relationships via $x->model

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ellgibug picture ellgibug  Â·  5Comments

gauravojha picture gauravojha  Â·  8Comments

wasid picture wasid  Â·  8Comments

Valonix picture Valonix  Â·  7Comments

matbeard picture matbeard  Â·  7Comments