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.