lundi 10 juin 2019

Shopping cart is the same for all users Laravel

I am working on a project with laravel, and I want every user to have his own cart which means if user one adds item to cart, deletes or update it should only show in his account without affecting other users. For now when a user adds item or deletes it shows in all users.

I have tried some solutions from other source but didn't work.

ProductController.php

public function cart()
{
    return view('cart');
}

public function addToCart($id)
{
    $products = Products_model::find($id);

    if(!$products) {

        abort(404);

    }

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

    // if cart is empty then this the first product
    if(!$cart) {

        $cart = [
                $id => [
                    "pro_name" => $products->pro_name,
                    "quantity" => 1,
                    "pro_price" => $products->pro_price,
                    "image" => $products->image
                ]
        ];

        session()->put('cart', $cart);

        return redirect()->back()->with('success', 'Product added to cart successfully!');
    }

    // if cart not empty then check if this product exist then increment quantity
    if(isset($cart[$id])) {

        $cart[$id]['quantity']++;

        session()->put('cart', $cart);

        return redirect()->back()->with('success', 'Product added to cart successfully!');

    }

    // if item not exist in cart then add to cart with quantity = 1
    $cart[$id] = [
        "pro_name" => $products->pro_name,
        "quantity" => 1,
        "pro_price" => $products->pro_price,
        "image" => $products->image
    ];

    session()->put('cart', $cart);

    return redirect()->back()->with('success', 'Product added to cart successfully!');
 }

public function update(Request $request)
{
    if($request->id and $request->quantity)
    {
        $cart = session()->get('cart');

        $cart[$request->id]["quantity"] = $request->quantity;

        session()->put('cart', $cart);

        session()->flash('success', 'Cart updated successfully');
    }
}

public function remove(Request $request)
{
    if($request->id) {

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

        if(isset($cart[$request->id])) {

            unset($cart[$request->id]);

            session()->put('cart', $cart);
        }

        session()->flash('success', 'Product removed successfully');
    }
}

I was expecting every user to have his own cart so can edit, delete and update without interfering other user.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire