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

Cart Laravel Package

shopper/cart

Laravel package for managing a shopping cart: add/update/remove items, handle quantities, totals, and cart persistence across requests or sessions. Designed to integrate into e‑commerce apps with a simple API and configurable storage.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require shopper/cart
    

    Verify shopper/core is auto-installed as a dependency.

  2. Service Provider Binding Register the package in config/app.php under providers:

    Shopper\Cart\CartServiceProvider::class,
    
  3. First Cart Operation

    use Shopper\Cart\Facades\Cart;
    
    // Add an item
    Cart::addItem('product_123', [
        'name' => 'Laravel T-Shirt',
        'price' => 29.99,
        'quantity' => 1,
    ]);
    
    // Get cart summary
    $cart = Cart::get();
    dd($cart['total']);
    
  4. Pipeline Configuration Publish the config and customize pipeline steps in config/cart.php:

    'pipeline' => [
        'steps' => [
            'subtotal',
            'tax',
            'discount',
            'shipping',
            'total',
        ],
    ],
    

Implementation Patterns

Core Workflow: Pipeline Extensions

Use Laravel’s service container to extend the pipeline dynamically:

// In a service provider (e.g., AppServiceProvider)
public function register()
{
    Cart::extend(function ($cart) {
        $cart->addPipelineStep('loyalty_discount', function ($cart) {
            if (auth()->user()->isGoldMember()) {
                return $cart->subtotal * 0.15; // 15% loyalty discount
            }
            return 0;
        });
    });
}

Integration with Laravel Features

  1. Events Listen to cart updates via Laravel’s event system:

    // Register in EventServiceProvider
    Cart::onUpdate(function ($cart) {
        event(new CartUpdated($cart));
    });
    
  2. Queues Offload heavy calculations to queues:

    Cart::calculate(function ($cart) {
        // This runs in a queue job
        return $cart->applyComplexDiscounts();
    });
    
  3. API Resources Format cart responses with Laravel’s API Resources:

    namespace App\Http\Resources;
    
    use Shopper\Cart\Facades\Cart;
    use Illuminate\Http\Resources\Json\JsonResource;
    
    class CartResource extends JsonResource
    {
        public function toArray($request)
        {
            return [
                'items' => Cart::get()['items'],
                'total' => Cart::get()['total'],
                'currency' => config('cart.currency'),
            ];
        }
    }
    

Multi-Tenant Support

Use Laravel’s context binding to manage tenant-specific carts:

// In a middleware or service provider
Cart::setContext('tenant_id_' . auth()->id());

Gotchas and Tips

Pitfalls

  1. Pipeline Order Matters

    • Steps execute in the order defined in config/cart.php. Reordering can break calculations.
    • Fix: Test pipeline steps incrementally.
  2. State Mutability

    • Pipeline steps modify the cart object in place. Side effects can cause unexpected behavior.
    • Fix: Clone the cart object before processing if needed:
      $cartClone = clone Cart::get();
      
  3. Missing Documentation

    • Undocumented methods or edge cases (e.g., addItem validation rules).
    • Fix: Use php artisan tinker to explore the API:
      Cart::addItem('test', ['price' => 10]);
      Cart::get();
      
  4. PHP 8.3 Requirements

    • Features like readonly properties or enums may cause issues in older Laravel versions.
    • Fix: Use a Docker setup with PHP 8.3 or polyfills.

Debugging Tips

  1. Log Pipeline Steps Add debug logging to track pipeline execution:

    Cart::extend(function ($cart) {
        $cart->addPipelineStep('debug', function ($cart) {
            \Log::debug('Pipeline state:', $cart->toArray());
            return 0;
        });
    });
    
  2. Isolate Pipeline Steps Temporarily disable steps to identify misbehaving logic:

    // In config/cart.php
    'pipeline' => [
        'steps' => ['subtotal', 'tax'], // Disable others for testing
    ],
    
  3. Handle Exceptions Gracefully Wrap pipeline execution in a try-catch:

    try {
        $cart = Cart::calculate();
    } catch (\Shopper\Cart\Exceptions\PipelineException $e) {
        \Log::error('Cart calculation failed:', ['error' => $e->getMessage()]);
        return response()->json(['error' => 'Cart processing error'], 500);
    }
    

Extension Points

  1. Custom Pipeline Steps Create reusable pipeline logic in a trait or service:

    // app/Services/CartExtensions.php
    namespace App\Services;
    
    use Shopper\Cart\Facades\Cart;
    
    class CartExtensions
    {
        public static function addBulkDiscount()
        {
            Cart::extend(function ($cart) {
                $cart->addPipelineStep('bulk_discount', function ($cart) {
                    $total = $cart->subtotal;
                    if ($total > 1000) {
                        return $total * 0.2; // 20% discount
                    }
                    return 0;
                });
            });
        }
    }
    
  2. Override Core Logic Replace default pipeline steps (e.g., tax calculation):

    Cart::extend(function ($cart) {
        $cart->removePipelineStep('tax');
        $cart->addPipelineStep('tax', function ($cart) {
            // Custom tax logic
            return $cart->subtotal * 0.08; // 8% flat tax
        });
    });
    
  3. Laravel Caching Integration Cache cart calculations to reduce pipeline overhead:

    use Illuminate\Support\Facades\Cache;
    
    $cartKey = 'cart_' . auth()->id();
    $cart = Cache::remember($cartKey, now()->addHours(1), function () {
        return Cart::calculate();
    });
    

Performance Quirks

  1. Avoid N+1 Queries If using Eloquent models, eager-load relationships:

    $items = Product::whereIn('id', $cartItemIds)->with('category')->get();
    
  2. Pipeline Caching Cache the entire pipeline result if calculations are expensive:

    Cache::remember('cart_total_' . auth()->id(), now()->addMinutes(5), function () {
        return Cart::get()['total'];
    });
    
  3. Queue-Based Calculations Offload heavy calculations to queues:

    Cart::calculate(function ($cart) {
        // This runs in a queue job
        return $cart->applyComplexPromotions();
    })->onQueue('high');
    

Laravel-Specific Tips

  1. Use Laravel Events Trigger events for cart updates:

    // In CartServiceProvider
    Cart::onUpdate(function ($cart) {
        event(new \App\Events\CartUpdated($cart));
    });
    
  2. Leverage Laravel Policies Secure cart operations with policies:

    // app/Policies/CartPolicy.php
    public function update(User $user, Cart $cart)
    {
        return $user->id === $cart->user_id;
    }
    
  3. API Testing Test cart endpoints with Laravel’s HTTP tests:

    public function test_add_to_cart()
    {
        $response = $this->postJson('/cart', [
            'product_id' => '123',
            'quantity' => 2,
        ]);
    
        $response->assertStatus(200)
                 ->assertJson(['total' => 59.98]);
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky