darryldecode / laravelshoppingcart

Shopping Cart Implementation for Laravel Framework
1.33k stars 436 forks source link

Order of the items in the cart #47

Open Sennik opened 8 years ago

Sennik commented 8 years ago

When I am updating the cart by adding or subtracting quantities (and loading the page with the cart again) the order of the items is changing. Is there a way to set the order? By example alphabetically on the items names? Or simply by the order the items are originally added to the cart?

darryldecode commented 8 years ago

Hello @Sennik , when an item/product in a cart is updated, it will pull the that item from the cart array and update its values and then push it back to the cart's array so the last updated item will always be on the last. If you want to sort it for example alphabetically, remember that when calling Cart::getContent(); it returns a Laravel Collection instance so you could use some of its sorting methods before displaying it to fit your needs. Like below:

$cartCollection = Cart::getContent();

$sorted = $cartCollection->sortBy(function ($product, $key) {
    // your sorting codes here
});

or you could sort it with raw php instead of laravel collections methods. For more information, this links might be useful: https://laravel.com/docs/5.1/collections#method-sort http://php.net/manual/en/function.asort.php

If you find any better alternatives on solving your case, feel free to suggest or do a PR. Thanks!

Sennik commented 8 years ago

Thank you :-)

Sennik commented 7 years ago

Loving this package but I ran into the same issue again. Sorting alphabetically is easy but most clients prefer the order of the items in the cart to stay te same after the make mutations.

Example: a cart with say 4 items. As soon as I cange the quantity of the second item the item is moved to the last position.

Quantity change is done by ajax and a partial replacement in the page (only the cart table). This works very well but sometimes I want to add multiple items by clicking at the 'plus' button. The items jumping down all the time is very annoying.

frezno commented 7 years ago

as mentioned before, you can use Laravels sort(), eg

public function getCart()
{
    $cartCollection = Cart::getContent();
    $cart = $cartCollection->sort();

    return view('shop.cart', compact('cart'));
}

and when changing the quantity the order of items in the cart remains the same as it has been before.

Chuby399 commented 1 year ago

Does anyone know a way to stop the order of the items from changing after it updates?