Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ecommerce Laravel Package

sonata-project/ecommerce

Symfony-based e-commerce platform from Sonata, offering a full shopping stack with product catalog, orders, payments, shipping, customer accounts, admin backend, and integrations. Built for extensibility and customization in complex commerce projects.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Require the package via Composer (note: legacy compatibility may be limited):

    composer require sonata-project/ecommerce:^3.5
    

    Run migrations (if applicable):

    php artisan migrate
    
  2. Bundle Setup Register the bundle in config/app.php under SonataEcommerceBundle (if using Symfony/Laravel bridge). Note: Ensure your Laravel app uses doctrine/dbal and doctrine/orm for Doctrine compatibility.

  3. Basic Usage

    • Products: Access via Product model (must extend Sonata\EcommerceBundle\Model\Product).
    • Cart: Use CartManager service (now compatible with Doctrine\Persistence\ManagerRegistry):
      $cartManager = app('sonata.ecommerce.cart.manager');
      $cartManager->add($product, $quantity);
      
    • Checkout: Extend Sonata\EcommerceBundle\Model\Order for custom logic.
  4. Admin Panel If using SonataAdmin, enable the dashboard via:

    # config/packages/sonata_ecommerce.yaml
    sonata_ecommerce:
        dashboard:
            groups:
                - { label: 'Products', icon: '<i class="fa fa-cube"></i>', items: ['sonata.ecommerce.product'] }
    

Implementation Patterns

Core Workflows

  1. Product Management

    • CRUD: Extend Sonata\EcommerceBundle\Entity\Product for custom fields.
    • Categories: Use Sonata\EcommerceBundle\Entity\Category for hierarchical taxonomies.
    • Inventory: Track stock via Product::getStock() and update with:
      $product->setStock($product->getStock() - $quantity);
      $product->getManager()->flush(); // Explicit flush due to Doctrine changes
      
  2. Shopping Cart

    • Session-Based: Cart persists via session (configure in config/packages/sonata_ecommerce.yaml).
    • Custom Logic: Override Sonata\EcommerceBundle\Manager\CartManager to add discounts or validation:
      public function add(Product $product, $quantity) {
          if (!$this->isProductAvailable($product, $quantity)) {
              throw new \RuntimeException('Out of stock');
          }
          parent::add($product, $quantity);
      }
      
  3. Checkout Process

    • Order Creation: Use OrderManager to create orders:
      $orderManager = app('sonata.ecommerce.order.manager');
      $order = $orderManager->create($cart, $customer);
      
    • Payment Integration: Hook into sonata.ecommerce.order.post_create event.
  4. Discounts & Promotions

    • Rules: Implement Sonata\EcommerceBundle\Model\DiscountInterface for custom rules.
    • Application: Apply discounts during cart checkout:
      $discount = $this->getDiscountService()->apply($cart);
      $cart->setDiscount($discount);
      $cart->getManager()->flush(); // Explicit flush
      
  5. API/Headless Use

    • REST Endpoints: Expose products/carts via Laravel routes.
    • GraphQL: Use return type resolvers (ensure Doctrine entities are properly mapped).

Integration Tips

  • Laravel-Specific:
    • Doctrine Registry: Bind Doctrine\Persistence\ManagerRegistry in config/services.php:
      'sonata.ecommerce.manager_registry' => \Doctrine\Persistence\ManagerRegistry::class,
      
    • Use Laravel’s Event system for order lifecycle hooks:
      event(new OrderCreated($order));
      
  • Frontend:
    • Use JavaScript to update cart via AJAX (e.g., fetch /cart/update).
    • Integrate with Vue/React for real-time updates.
  • Testing:
    • Mock CartManager and OrderManager in PHPUnit:
      $this->mock(CartManager::class)->shouldReceive('add')->once();
      

Gotchas and Tips

Pitfalls

  1. Doctrine Registry Change

    • Breaking Change: Symfony\Bridge\Doctrine\RegistryInterface replaced with Doctrine\Persistence\ManagerRegistry. Fix: Update service bindings and ensure your Laravel app uses the new registry:
      $registry = app('doctrine')->getManagerRegistry();
      
    • Legacy Code: Older Sonata bundles may still use the deprecated registry.
  2. Abandoned Package Risks

    • No Active Maintenance: Expect no bug fixes or Laravel 10 compatibility.
    • Workarounds: Fork the repo or use alternatives like bagisto or laravel-shoppingcart.
  3. Session Cart Issues

    • Stale Data: Cart may persist across sessions if not cleared properly. Fix: Implement CartManager::clear() in logout middleware.
  4. Database Schema

    • Legacy Migrations: Tables like sonata_ecommerce_product may not align with Laravel conventions. Fix: Create custom migrations or use Doctrine migrations via doctrine/dbal.
  5. Admin Panel Quirks

    • Broken UI: SonataAdmin templates may not render correctly in Laravel. Fix: Override Twig templates or use Laravel Blade via laravel-bridge.

Debugging Tips

  1. Cart Not Updating

    • Check if sonata.ecommerce.cart.session is configured in config/packages/sonata_ecommerce.yaml.
    • Verify session driver in .env (SESSION_DRIVER=file for testing).
    • Ensure ManagerRegistry is properly injected:
      $this->registry = app('doctrine')->getManagerRegistry();
      
  2. Product Not Saving

    • Ensure Product extends Sonata\EcommerceBundle\Model\Product and annotations are present.
    • Check for validation errors with:
      $errors = $validator->validate($product);
      
    • Explicitly flush changes:
      $product->getManager()->flush();
      
  3. Order Not Creating

    • Validate OrderManager dependencies (e.g., Customer, PaymentMethod).
    • Enable debug mode (APP_DEBUG=true) to log missing services.
  4. Event Listeners Failing

    • Register listeners in EventServiceProvider:
      protected $listen = [
          'sonata.ecommerce.order.post_create' => [
              \App\Listeners\OrderCreatedListener::class,
          ],
      ];
      

Extension Points

  1. Custom Fields

    • Add fields to Product via Doctrine extensions or Laravel accessors:
      public function getFormattedPrice() {
          return '$' . $this->price;
      }
      
  2. Payment Gateways

    • Extend Sonata\EcommerceBundle\Model\PaymentMethod or create a wrapper service:
      class StripePaymentGateway {
          public function charge(Order $order) {
              $entityManager = $order->getManager();
              // Integrate with Stripe API
          }
      }
      
  3. Shipping Methods

    • Implement Sonata\EcommerceBundle\Model\ShippingMethodInterface for custom logic.
  4. Frontend Templates

    • Override Sonata templates in resources/views/vendor/sonata_ecommerce/ (if using Blade).
    • For Twig, extend base templates in templates/SonataEcommerceBundle/.
  5. Testing Utilities

    • Create helper traits for testing:
      trait EcommerceTestTrait {
          protected function createProduct() {
              $product = Product::factory()->create();
              $product->setManager(app('doctrine')->getManager());
              return $product;
          }
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager