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

isapp/laravel-cart

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Run composer require isapp/laravel-cart and publish the config with php artisan vendor:publish --provider="Isapp\LaravelCart\CartServiceProvider" --tag="config".
  2. First Use Case: Add a cart to a guest user:
    use Isapp\LaravelCart\Facades\Cart;
    
    // Add an item (e.g., a product model)
    Cart::add([
        'id' => 1,
        'name' => 'Product Name',
        'price' => 19.99,
        'quantity' => 1,
    ]);
    
  3. Retrieve Cart: Access the cart anywhere in your app:
    $cart = Cart::get();
    $items = $cart->items;
    $total = $cart->total;
    

Key Files to Review

  • Config: config/laravel-cart.php (storage driver, session/DB settings).
  • Facade: Isapp\LaravelCart\Facades\Cart (primary API entry point).
  • Migrations: Published with php artisan vendor:publish --tag="migrations" (if using DB storage).

Implementation Patterns

Core Workflows

1. Item Management

  • Add Items: Chainable methods for flexibility:
    Cart::add($item)->associate('App\Models\Product')->save();
    
  • Update/Remove: Use IDs or model associations:
    Cart::update(1, ['quantity' => 2]);
    Cart::remove(1);
    
  • Batch Operations: Clear or empty the cart:
    Cart::clear(); // Removes all items
    Cart::empty(); // Resets cart but keeps session
    

2. Storage Integration

  • Session Driver: Default for simplicity (no DB needed).
  • Database Driver: Publish migrations and configure in config/laravel-cart.php:
    'driver' => 'database',
    'table' => 'cart_items',
    
    Sync carts between sessions/DB with:
    Cart::sync();
    

3. Model Associations

  • Link cart items to Eloquent models for rich queries:
    Cart::add($product)->associate(Product::class);
    $cartItems = Cart::items()->where('quantity', '>', 1)->get();
    

4. Guest vs. Authenticated Users

  • Guest Cart: Persists via session by default.
  • Authenticated Users: Auto-sync to DB when user logs in:
    event(new UserLoggedIn($user)); // Trigger sync
    
    Configure in config/laravel-cart.php:
    'sync_on_login' => true,
    'user_model' => App\Models\User::class,
    

5. Price Calculations

  • Use built-in methods for totals/taxes:
    $subtotal = Cart::subtotal();
    $tax = Cart::tax(0.1); // 10% tax
    $total = Cart::total();
    
  • Customize with config/laravel-cart.php:
    'currency' => 'USD',
    'precision' => 2,
    

6. API/Controller Integration

  • Example Controller:
    public function addToCart(Request $request, Product $product) {
        Cart::add($product)->save();
        return back()->with('success', 'Added to cart!');
    }
    
  • API Response:
    return response()->json(Cart::get());
    

7. Views

  • Share cart data in Blade:
    @inject('cart', 'Isapp\LaravelCart\Facades\Cart')
    <div>Items: {{ $cart->count() }}</div>
    
  • Use the cart helper for concise syntax:
    @cart(['item' => $cart->items])
    

Gotchas and Tips

Pitfalls

  1. Session vs. Database Sync:

    • If sync_on_login is true, ensure the UserLoggedIn event is fired (or manually call Cart::sync()).
    • Debug Tip: Check config/laravel-cart.php for sync_on_login and verify event listeners.
  2. Model Association Mismatches:

    • If associating items with models, ensure the model’s id matches the cart item’s id. Use associate() before save():
      Cart::add($product)->associate(Product::class)->save();
      
    • Error: ModelNotFoundException if the associated model doesn’t exist.
  3. Precision Issues:

    • Floating-point arithmetic can cause rounding errors. Use Cart::precision() to enforce decimal places:
      Cart::precision(4); // For cents
      
    • Fix: Configure precision in config/laravel-cart.php.
  4. Guest Cart Persistence:

    • Session-based carts are lost on browser close. For persistent guest carts, use DB storage or a cookie fallback.
  5. Migration Conflicts:

    • If publishing migrations, check for existing cart_items tables to avoid conflicts. Run php artisan migrate after publishing.

Debugging Tips

  • Log Cart Contents:
    \Log::info('Cart:', ['items' => Cart::get()->items]);
    
  • Check Storage Driver:
    • For session issues, inspect session()->all().
    • For DB issues, query the cart_items table directly:
      SELECT * FROM cart_items WHERE user_id IS NULL; -- Guest carts
      

Extension Points

  1. Custom Storage:

    • Extend the Isapp\LaravelCart\Contracts\CartStorage interface to support Redis or other drivers.
  2. Event Hooks:

    • Listen for cart events (e.g., cart.item.added) to trigger notifications or analytics:
      Cart::on('item.added', function ($item) {
          // Send email or log event
      });
      
  3. Validation:

    • Validate cart items before adding:
      use Isapp\LaravelCart\Exceptions\ValidationException;
      
      try {
          Cart::add($item)->validate(function ($item) {
              return $item['quantity'] > 0;
          });
      } catch (ValidationException $e) {
          // Handle error
      }
      
  4. Testing:

    • Mock the Cart facade in tests:
      $this->mock(Isapp\LaravelCart\Facades\Cart::class)->shouldReceive('get')->andReturn($mockCart);
      
    • Use Cart::flush() to reset test carts.
  5. Performance:

    • For large carts, optimize DB queries by eager-loading associations:
      $cart = Cart::items()->with('product')->get();
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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