Search code examples
phplaravel

How to Handle Individual Shopping Carts for Authenticated Users in Laravel


I have a Laravel application where users can add products to their shopping cart. Currently, I am storing the cart items in the session, but this approach causes issues because the cart data is shared across all users. I want to modify the implementation so that each authenticated user has their own separate cart.

Current Implementation

Cart.php

namespace App;

class Cart
{
    public $items = null;
    public $totalQty = 0;
    public $totalPrice = 0;

    public function __construct($oldCart)
    {
        if ($oldCart) {
            $this->items = $oldCart->items;
            $this->totalQty = $oldCart->totalQty;
            $this->totalPrice = $oldCart->totalPrice;
        }
    }

    public function add($item, $id)
    {
        $storedItems = ['qty' => 0, 'price' => $item->price, 'item' => $item];
        if ($this->items) {
            if (array_key_exists($id, $this->items)) {
                $storedItems = $this->items[$id];
            }
        }
        $storedItems['qty']++;
        $storedItems['price'] = $item->ucp * $storedItems['qty'];
        $this->items[$id] = $storedItems;
        $this->totalQty++;
        $this->totalPrice += $item->ucp;
    }
}

CartController.php

namespace App\Http\Controllers;

use App\Cart;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class CartController extends Controller
{
    public function addToCart(Request $request)
    {
        $id = $request->product_id;
        $product = Product::find($id);
        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);
        
        if ($request->get_quantity) {
            while ($request->get_quantity > 0) {
                $cart->add($product, $product->id);
                $request->get_quantity--;
            }
        } else {
            $cart->add($product, $product->id);
        }

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

        return Session::get('cart')->totalQty;
    }
}

How can I modify my existing code to handle carts individually for each authenticated user?


Solution

  • You can make it unique with userId. Something like below

    $request->session()->put('cart'.$userId, $cart);
    

    when you need to get that cart, get it like below.

    return Session::get('cart'.$userId)->totalQty;
    

    Now let me explain you.

    Am just concatenating userId with cart so it becomes unique. when first user is logged in and i need to get his cart. so i simply right below.

    Session::get('cart'.Auth::id())->totalQty;
    

    that's how you will get cart of the related user only.

    You can also use some laravel cart package. Let me know if you need one in the comment section.