hardevine / LaravelShoppingcart

A simple shopping cart implementation for Laravel
MIT License
348 stars 120 forks source link

How can I get cart item by product id #18

Closed officialmmt closed 3 years ago

officialmmt commented 3 years ago

Hi, I trying to get a product with id without use Cart::content() foreach. It can be possible to get a product like this?

atundo commented 3 years ago

Hi,

Look at the search function example:

https://github.com/hardevine/LaravelShoppingcart#cartsearch

Kessir commented 3 years ago

Like @atundo said, Cart::search() is the official way of getting the cart item.

Unfortunately it can be quite inefficient if you need to do it a lot. My solution is to guess the $rowId myself using this function from the library:

protected function generateRowId($id, array $options)
{
    ksort($options);
    return md5($id . serialize($options));
}

If you are not using the options array when adding items to cart, you can simplify it to :

$rowId =  md5($productId . serialize([]));
$cartItem = Cart::get($rowId);