Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

croftCoder's avatar

Persist user cart across sessions

namespace App\Http\Controllers;

// removed imports for brevity

class CartController extends Controller
{
    protected $cartService;
    protected $pricingService;

    public function __construct(CartService $cartService, PricingService $pricingService)
    {
        $this->cartService = $cartService;
        $this->pricingService = $pricingService;

        // Listen for session regeneration events to transfer cart data
        Event::listen(SessionRegenerated::class, function ($event) {
            $oldSessionId = $event->old;
            $newSessionId = $event->session->getId();

            $cart = session()->get("cart_$oldSessionId");
            session()->put("cart_$newSessionId", $cart);
        });
    }

    // reduced code for simplicity
}

// schema for carts table

Schema::create('carts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->nullable()->constrained('users');
    $table->string('session_id')->nullable();
    $table->decimal('discount', 8, 2)->default(0);
    $table->decimal('tax', 8, 2)->default(0);
    $table->decimal('shipping_cost', 8, 2)->default(0);
    $table->timestamp('expires_at')->nullable();
    $table->timestamps();
});

i want to persist cart data across sessions so that reloading the page even after session has been regenerated user won't lose cart.

0 likes
3 replies
chiefguru's avatar

Hi @croftcoder, we store the cart object in the database in a very similar table to your carts table however where you have the session_id we have a BLOB containing the serialised cart.

If the cart isn't in the session we simply load it from the db and after a few validation checks add to the session.

JussiMannisto's avatar

Don't store session ID in the cart model. Store the cart model ID in the session.

Models in an MVC architecture shouldn't worry about sessions, they should only implement business logic. Let controllers handle sessions.

martinbean's avatar

i want to persist cart data across sessions

@croftcoder So don’t store it in the session.

You should use a cookie or something to store the cart identifier. This will then persist across the user logging in and out. However, you also need to be careful of that. If I log out of a website, I wouldn’t expect my cart to stay around.

Please or to participate in this conversation.