databasesymfonysession

How to save my cart to my database in symfony?


Im trying to come up with a way to save my cart to my database as a order, but cant figure out how, the tricky part for me is how to fill the data of my cart items in the order, i want the order to be just a text value so its easier to save.

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use App\Entity\Category;
use App\Entity\Product;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Session\Session;

final class ProductController extends AbstractController
{
#[Route('/cart/add/{id}', name: 'app_product')]
public function addToCart(EntityManagerInterface $entityManager, Request $request, int $id): Response
{
    $session = $request->getSession();

    // Get current cart or initialize empty array
    $cart = $session->get('cart', []);

    // Fetch product by id
    $product = $entityManager->getRepository(Product::class)->find($id);

    if (!$product) {
        throw $this->createNotFoundException('Product not found');
    }

    $idForRoute = $product->getCategory()->getId();
    $productId = $product->getId();

    // Check if product already in cart; increment quantity or add new
    if (isset($cart[$productId])) {
        $cart[$productId]['quantity']++;
    } else {
        $cart[$productId] = [
            'id'       => $productId,
            'name'     => $product->getName(),
            'price'    => $product->getPrice(),
            'quantity' => 1,
        ];
    }

    // Save updated cart back to session
    $session->set('cart', $cart);

    // Redirect to product category show page or wherever appropriate
    return $this->redirectToRoute('app_product_show', ['id' => $idForRoute]);
    }


    #[Route('/cart', name: 'app_cart')]
    public function cart(EntityManagerInterface $entityManager, Request $request): Response
    {
        $session = $request->getSession();

        $cart = $session->get('cart', []);

        return $this->render('product/cart.html.twig', [
            'cart' => $cart,
        ]);
    }

this is what i have right now but, i got no clue how to save it to my DB could anyone help?

i tried looking it up on internet but cant find a clear answer which i can implement here


Solution

  •     #[Route('/cart/save', name: 'app_cart_save')]
        public function saveOrder(EntityManagerInterface $em, Request $request): Response
        {
        $session = $request->getSession();
        $cart = $session->get('cart', []);
    
        if (empty($cart)) {
            $this->addFlash('warning', 'Your cart is empty!');
            return $this->redirectToRoute('app_cart');
        }
    
        $orderText = "";
        $totalPrice = 0.0;
    
        foreach ($cart as $item) {
            $lineTotal = $item['price'] * $item['quantity'];
            $orderText .= sprintf(
                "Product: %s | Quantity: %d | Unit Price: €%.2f | Line Total: €%.2f\n",
                $item['name'],
                $item['quantity'],
                $item['price'],
                $lineTotal
            );
            $totalPrice += $lineTotal;
        }
    
        $orderText .= sprintf("\nTotal Price: €%.2f", $totalPrice);
    
        $order = new Order();
        $order->setTotalPrice($totalPrice);
        $order->setOrderDetails($orderText);
        $order->setCreatedAt(new \DateTimeImmutable());
    
        $em->persist($order);
        $em->flush();
    
        $session->remove('cart');
    
        $this->addFlash('success', 'Order saved successfully!');
    
        return $this->redirectToRoute('app_cart');
        }
    

    i made a little demo for myself to see if i could figure it out and i think this should also work for you make sure to implement the code i sent u and your entity 'Order' would have to look something like this = id, orderDetails, totalPrice, createdAt