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

Laravel Cart Laravel Package

binafy/laravel-cart

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require binafy/laravel-cart
    php artisan vendor:publish --provider="Binafy\Cart\CartServiceProvider" --tag="config"
    php artisan migrate
    
    • Verify config/cart.php is published and updated with your preferred driver (e.g., session, database, or redis).
  2. First Use Case: Add an item to the cart via the facade:

    use Binafy\Cart\Facades\Cart;
    
    Cart::add([
        'id' => 'product_123',
        'name' => 'Example Product',
        'qty' => 1,
        'price' => 9.99,
        'options' => ['color' => 'blue']
    ]);
    
    • Check the cart contents:
    $cartItems = Cart::get();
    

Where to Look First

  • Configuration: config/cart.php (drivers, default settings).
  • Facade: Binafy\Cart\Facades\Cart (core methods like add(), update(), remove()).
  • Model: Binafy\Cart\Models\Cart (if using the database driver).
  • Events: CartItemAdded, CartItemUpdated, CartItemRemoved (in app/Events).

Implementation Patterns

Core Workflows

  1. Adding Items:

    • Use Cart::add() with an associative array (required keys: id, qty, price).
    • Optional: name, options, associatedModel (for database-driven carts).
    • Example with dynamic pricing:
      $price = $product->applyDiscount();
      Cart::add([
          'id' => $product->id,
          'qty' => $request->qty,
          'price' => $price,
          'options' => ['discount_code' => $request->code]
      ]);
      
  2. Updating/Cart Management:

    • Update quantity: Cart::update($id, ['qty' => 5]).
    • Remove item: Cart::remove($id).
    • Clear cart: Cart::clear().
  3. Driver-Specific Patterns:

    • Session Driver: Lightweight, stateless (default). Use for simple carts.
      Cart::setDriver('session');
      
    • Database Driver: Persistent across sessions (requires cart_items table).
      Cart::setDriver('database');
      Cart::add(['id' => '1', 'associatedModel' => Product::class]);
      
    • Redis Driver: Scalable for distributed systems.
      Cart::setDriver('redis');
      
  4. Checkout Flow:

    • Validate cart: Cart::validate() (checks for stock, prices, etc.).
    • Process payment (integrate with Stripe/PayPal) using cart subtotal:
      $subtotal = Cart::subtotal();
      $tax = Cart::tax();
      $total = Cart::total();
      
    • Clear cart post-checkout: Cart::clear().

Integration Tips

  • Blade Views:
    @foreach (Cart::get() as $item)
        <div>{{ $item->name }} ({{ $item->qty }} x ${{ $item->price }})</div>
    @endforeach
    
  • API Responses:
    return response()->json([
        'cart' => Cart::get(),
        'subtotal' => Cart::subtotal(),
        'tax' => Cart::tax(),
    ]);
    
  • Middleware: Use Binafy\Cart\Http\Middleware\CartMiddleware to attach cart data to requests:
    $middleware = [\Binafy\Cart\Http\Middleware\CartMiddleware::class];
    
  • Events: Listen for cart changes to sync inventory or send notifications:
    CartItemAdded::dispatch($item);
    

Gotchas and Tips

Pitfalls

  1. Driver Mismatches:

    • If using the database driver, ensure the cart_items table exists and the associatedModel is correctly set.
    • Fix: Run migrations and verify table structure:
      php artisan migrate
      
    • Debug: Check config/cart.php for driver and connection settings.
  2. Session Driver Limitations:

    • Cart data is lost if the session expires or the user closes the browser.
    • Workaround: Use session:driver=database in .env for persistence.
  3. ID Collisions:

    • Custom id fields must be unique per cart item. Reusing IDs (e.g., product IDs) without context can cause overwrites.
    • Solution: Use composite IDs (e.g., product_id_user_id) or leverage options for disambiguation.
  4. Tax/Subtotal Calculations:

    • Default calculations assume flat rates. Override via config:
      'tax' => [
          'enabled' => true,
          'rate' => 0.08, // 8%
          'calculation' => 'Binafy\Cart\Calculations\Tax::class',
      ],
      
    • Tip: Extend Binafy\Cart\Calculations\Tax for dynamic rates (e.g., per-product taxes).
  5. Performance with Database Driver:

    • Large carts may slow queries. Optimize with indexes on cart_id and id.
    • Query: Add ->with('product') to eager-load relationships if using associatedModel.

Debugging

  • Log Cart Contents:
    \Log::debug('Cart contents:', ['items' => Cart::get()->toArray()]);
    
  • Check Driver Storage:
    • Session: Inspect storage/framework/sessions.
    • Database: Query cart_items table.
    • Redis: Use redis-cli to inspect keys (e.g., cart:user_1).

Configuration Quirks

  1. User Context:

    • By default, carts are user-agnostic. For user-specific carts:
      Cart::setUser(auth()->id()); // Set user ID
      
    • Config: Set 'user_id_column' => 'user_id' in config/cart.php for database driver.
  2. Custom Models:

    • Extend Binafy\Cart\Models\Cart or Binafy\Cart\Models\CartItem for additional fields:
      php artisan make:model CartItemExtension --extends=Binafy\Cart\Models\CartItem
      
    • Migration: Add fields to cart_items table.
  3. Caching:

    • Enable Redis caching for database driver to reduce DB load:
      'cache' => [
          'enabled' => true,
          'driver' => 'redis',
      ],
      

Extension Points

  1. Custom Drivers:

    • Implement Binafy\Cart\Contracts\Driver:
      class MyDriver implements Driver {
          public function get($userId = null) { ... }
          public function add(array $item) { ... }
          // ... other methods
      }
      
    • Register in config/cart.php:
      'drivers' => [
          'my_driver' => \App\Drivers\MyDriver::class,
      ],
      
  2. Validation Rules:

    • Override default validation (e.g., max quantity) by extending Binafy\Cart\Rules\CartRule:
      use Binafy\Cart\Rules\CartRule;
      
      class MaxQuantityRule extends CartRule {
          public function passes($errorBag, $attribute, $value) {
              return $value <= 10; // Max 10 items
          }
      }
      
    • Bind in AppServiceProvider:
      Validator::extend('max_quantity', function ($attribute, $value, $parameters, $validator) {
          return (new MaxQuantityRule())->passes($validator, $attribute, $value);
      });
      
  3. Webhooks/Events:

    • Listen for CartItemAdded to update inventory:
      CartItemAdded::listen(function ($event) {
          Product::find($event->item->id)->decrement('stock', $event->item->qty);
      });
      
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.
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
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui