Jonilo5
Jonilo5

Reputation: 45

PHP shopping cart with laravel - quantity issue

I am working on a laravel-shopping site project, and I have problems with the quantity of the product in the cart. I am relatively new to Laravel, so things gets more complicated for me... The thing is that I can't really loop (and look for) simular products in a effective way.

But when I press the "Add to cart"-button, this function will run:

public function cart(Product $product){

    $cart = session()->get('cart');

    // If Cart is empty, add a new array in the session
    if ($cart == []) {
        $cart[] = $product;
        session()->put('cart', $cart);
    }else{
        // else if not empty, loop the cart and look if similar product is in the cart.
        for ($i = 0; $i <= count($cart); $i++) {

            $array_cart = json_decode($cart[$i], true);
            if ($product->id == $array_cart["id"]) {
                    $array_cart["id"] += 1;
            }else{
                $cart[] = $product;
                session()->put('cart', $cart);
            } 
        }
    }

    return back();
}

The products are objects, and I am not sure how to loop to find the id of the product to match the array-products id. I tried json_decode() to see if that would make it into an array, but I might be wrong here because when I return the value it was the same "object". For example a single product in the cart can look like this:

    [{"id": 4,
"name": "HP Desktop",
"description": "Ordinary desktop",
"category": "Desktop",
"price": 1,
"views": 63,
"created_at": "2016-04-11 14:42:58",
"updated_at": "2016-05-27 09:12:59"
}]

Upvotes: 2

Views: 2104

Answers (1)

Robin Dirksen
Robin Dirksen

Reputation: 3422

You need to run a foreach loop, this will loop through all the objects.

So for example you can run this code in a controller to get the id:

foreach($products as $product) {
    dump($product->id);
}

Or you can use this in a blade view.

@foreach($products as $product)
    dump($product->id);
@endforeach

I suggest you to add a quantity in your object, than you can update the quantity and calculate the price.

public function cart(Product $product){

    $cart = session()->get('cart');

    // If Cart is empty, add a new array in the session
    if ($cart == []) {
        $cart[] = $product;
        session()->put('cart', $cart);
    }else{
        // else if not empty, loop the cart and look if similar product is in the cart.
        foreach ($cart as $product_item) {
            if ($product->id == $product_item["id"]) {
                    $product_item["quantity"] += 1;
                    $found = true;
            }
        }

        if($found !== true) {
             $cart[] = $product;
             session()->put('cart', $cart);
        }
    }

    return back();
}

Hope this works!

Upvotes: 3

Related Questions