Closed victorighalo closed 4 years ago
public function addItem(Buyable $product, $qty = 1, $params = []): \Vanilo\Cart\Contracts\CartItem
{
$item = $this->items()->ofCart($this)->byProduct($product)->first();
if ($item) {
$item->quantity += $qty;
$item->save();
} else {
$item = $this->items()->create(
array_merge(
$this->getDefaultCartItemAttributes($product, $qty),
$this->getExtraProductMergeAttributes($product),
$params['attributes'] ?? []
)
);
}
$this->load('items');
return $item;
}
This seems to be the part that increments the cart item quantity if it exists. Can we have an alternative to add a new item to cart instead of increasing quantity?
I think that's possible. So that I get your context, can you please describe the use case in a little bit more details?
I think that's possible. So that I get your context, can you please describe the use case in a little bit more details?
A shopper wants to add a product with variant Color:Red and Size:XL, the same shopper also wants to add another of the same product with variant Color:Blue and Size:XXL. The shopper wants to see these as two distinct items in cart and as distinct items as an order
Ah cool, I get it. It's basically the product variants problem, see also vanilophp/framework#62 for more details.
How do you distinguish between Color and Size variants? Are you using the properties package or something else?
I made my own variants module. Variants have foreign key relationships with the product model.
However, even without variants, is this possible currently or do can I extend the Cart model like I have done with the Product model.
Absolutely possible. You only need to replace the Cart
model (not the facade!) and overwrite the addItem
method with your version.
Steps:
App\Cart
App\Cart
to extend Vanilo\Cart\Models\Cart
addItem
method in App\Cart
// app/Providers/AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider; use Vanilo\Cart\Contracts\Cart as CartContract;
class AppServiceProvider extends ServiceProvider { public function boot() { $this->app->concord->registerModel( CartContract::class, \App\Cart::class ); } }
This way, your custom method will be used, even if you're invoking the cart facade's `Cart::addItem` method.
More details: https://vanilo.io/how-to/use-custom-models-in-your-application
Let me know if it worked :bowing_man:
Could you manage to achieve the functionality?
Hey Attila, i had the same Problem and could solve the problem. Excellent help. Thank you!
As of Laravel 7.x it needs to be
class Cart extends \Vanilo\Cart\Models\Cart { public function addItem(Buyable $product, $qty = 1, $params = []): \Vanilo\Cart\Contracts\CartItem
(with \ before Vanilo)
Is it possible to add an item more than once to the cart and it won't increase the quantity but add a separate item to cart.