1
votes

I am making laravel shopping cart and now working with laravel session.
My imagine is:

  1. If cart session is null:
    Adding first product
  2. If not:
    Check request product's ID, if it is not existing product's ID:
    -> push to cart session array
    If not:
    -> don't push to cart session array

I can push product in to session but with the first product, when I add one more time the same product, it was added, but the 2nd, 3rd...product work fine.
I try many time but not found the way to solve. Can you help me?
This is my CartController with add method*

public function add(Request $request)
{
  $cartItems = session('cart');
  $productInfoToCart = array(
    "id" => request('id'),
    "name" => request('name'),
    "code" => request('code'),
    "price" => request('price')
  );
  if ($cartItems !== null){
    if (array_search(request('id'), array_column($cartItems, 'id'))) {
      return redirect ('/cart')->with('status', 'Product exists, you can change quantity before payment');
    } else {
    $request->session()->push('cart', $productInfoToCart);
    $request->session()->flash('status', 'Product added to cart');

    return redirect('/cart');
    }
  } else {
    $request->session()->push('cart', $productInfoToCart);
    $request->session()->flash('status', 'First Product added to cart');

    return redirect('/cart');
  }
}
2

2 Answers

0
votes

You should create a class Cart and not coding the logic of the cart in the controller. You are storing the data in the sessions but tomorow you may store it somewhere else and this code will not work anymore so try to not couple the logic with a storage system.

You can also easily simplify your code (no useless "if else" when you use return statment in it)

public function add()
{
    $cartItems = session('cart');
    $productInfoToCart = array(
      "id" => request('id'),
      "name" => request('name'),
      "code" => request('code'),
      "price" => request('price')
    );
    if ($cartItems !== null){
        if (isset($cartItems[request('id')]){
            return redirect ('/cart'); //...
        }
        $cartItems[request('id')] = $productInfoToCart;
        $request->session()->put('cart', $cartItems);
        $request->session()->flash('status', 'Product added to cart');   
        return redirect('/cart');
    }
    $cartItems[request('id')] = $productInfoToCart;
    $request->session()->put('cart', $cartItems);
    $request->session()->flash('status', 'First Product added to cart');
    return redirect('/cart');
}
0
votes

Finally I found the way to solve, just edit this line:

if (array_search(request('id'), array_column($cartItems, 'id')))  

to:

if (array_search(request('id'), array_column($cartItems, 'id')) !== false)  

because maybe the old line will return the key of search, not the logic result, so I could not run the next logic command.