LaravelShoppingcart icon indicating copy to clipboard operation
LaravelShoppingcart copied to clipboard

Associating Multiple Models causing strange issues

Open colinbarstow opened this issue 6 years ago • 3 comments

I am not sure if this Package is even live, as there are so many open issues, so my first question is exactly that, is this being looked after?

There is an issue, a very strange little problem that is driving me round the bend. To start with I have 3 models that are purchasable.

Meals Seasonings Offers

When adding to cart, I have this little method to determine which model is being purchased and associate that model with the cart item.

public function store(Request $request)
{
    $quantity = 1;

    switch($request->type){
        case 'meal':
            $model = Meal::find($request->id);
            $class = Meal::class;
            break;
        case 'seasoning':
            $model = Seasoning::find($request->id);
            $class = Seasoning::class;
            break;
        case 'offer':
            $model = Offer::find($request->id);
            $class = Offer::class;
            break;
    }
    $item = Cart::add($model->id, $model->title, $quantity, $model->price);
    $item->associate($class);

    return Cart::count();
}

cart items are added fine and models are associated with fine, however, let's say I have a seasoning with the id of 1 and an offer with the id of 1. I want to add both to one cart instance, here's what happens.

I add the seasoning. Added to cart and model associated successfully.

I then add the offer. Added to cart and model associated successfully, however, the seasoning instance is now associated with the Offer model and I have an offer with the quantity of 2.

See screen shots

Seasoning added:

image

Offer added with same id:

image

Any ideas? Did anyone experience any similar issues?

Any help would be very much appreciated.

colinbarstow avatar May 30 '18 14:05 colinbarstow

id has to be unique in the cart.

So maybe you have to concat the modelname and the id to be sure that the id is unique in the cart

sbourdette avatar Sep 16 '18 14:09 sbourdette

@colinbarstow Can you explain what approach you take after this limitation? Because if I try to pass a custom ID to the buyable item, then how I can retrieve the model?. I have to overload the find method? Use a uniq ID instead if auto incremental value ? I should really appreciate your feedback.

jdcifuentes avatar Nov 06 '19 01:11 jdcifuentes

For anyone who comes up with this issue, a quick solution is to increase the id starting value in the tables. in Laravel 8 you have the new "$table->id()->from(200000);" method where you can set a starting value for your id field.

shinanmhd avatar Sep 10 '21 03:09 shinanmhd