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

Ti Ext Cart Laravel Package

tastyigniter/ti-ext-cart

TastyIgniter Cart extension adds a flexible shopping cart and checkout for restaurants: delivery/pickup orders, tips/taxes via cart conditions, menu scheduling, inventory and order management, payment gateways (PayPal/Stripe/COD), notifications and emails.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tastyigniter/ti-ext-cart
    php artisan vendor:publish --provider="TastyIgniter\Cart\CartServiceProvider"
    php artisan migrate
    
    • Publish the package’s assets (config, migrations, views) and run migrations to set up the database tables.
  2. Configuration:

    • Update .env with required settings (e.g., CART_SESSION_KEY, payment gateway keys).
    • Configure cart behavior in config/cart.php (e.g., default currency, tax rules, session handling).
  3. First Use Case:

    • Add a Menu Item to Cart:
      use TastyIgniter\Cart\Facades\Cart;
      
      $menuId = 1;
      $quantity = 2;
      $options = ['size' => 'large']; // Optional menu options
      
      Cart::add($menuId, $quantity, $options);
      
    • Display the cart in a Blade view:
      @include('cart::partials.cart-summary')
      
  4. Quick Checkout:

    • Use the built-in checkout route:
      Route::get('/checkout', [CheckoutController::class, 'show'])->name('checkout.show');
      
    • Process the order via the Order model or controller methods provided by the package.

Implementation Patterns

Core Workflows

  1. Cart Management:

    • Adding Items:
      Cart::add($menuId, $quantity, $options, $locationId);
      
      • Supports optional locationId for multi-location businesses (e.g., restaurants with multiple branches).
    • Updating/Clearing:
      Cart::update($menuId, $newQuantity);
      Cart::clear();
      
    • Conditions: Apply cart conditions (e.g., discounts, taxes) via the CartCondition model or config:
      Cart::applyCondition('discount_10_percent', $customerId);
      
  2. Order Processing:

    • Create Order:
      $order = Cart::checkout([
          'customer_id' => auth()->id(),
          'delivery_method' => 'pickup',
          'payment_method' => 'stripe',
          'notes' => 'Rush order',
      ]);
      
    • Order Status Workflows: Use the StatusWorkflow model to define custom status transitions (e.g., pendingacceptedshipped):
      $workflow = StatusWorkflow::where('name', 'default')->first();
      $order->updateStatus('accepted', $workflow);
      
  3. Inventory Management:

    • Stock Validation:
      if (!Cart::validateStock($menuId, $quantity)) {
          return back()->withError('Item out of stock!');
      }
      
    • Override Out-of-Stock: Temporarily allow sales for out-of-stock items via admin panel with a duration setting.
  4. Payment Integration:

    • Gateway Setup: Configure payment gateways in the admin panel (e.g., Stripe, PayPal, Cash on Delivery).
    • Process Payment:
      $payment = $order->processPayment($gateway, $amount);
      
  5. Real-Time Notifications:

    • Order Popups: Enable admin notifications for new orders via the OrderNotification model:
      event(new OrderCreated($order));
      
    • Email Alerts: Customize email templates in resources/views/vendor/cart/emails/.

Integration Tips

  1. Multi-Location Support:

    • Use the location_id parameter in cart methods to manage separate inventories per branch:
      Cart::setLocation($locationId);
      
  2. Custom Menu Options:

    • Extend the MenuOption model to add validation or business logic:
      public function validateOption($value, $menuOption)
      {
          if ($menuOption->type === 'select' && !in_array($value, $menuOption->values)) {
              throw new \InvalidArgumentException('Invalid option selected.');
          }
          return true;
      }
      
  3. Dynamic Pricing:

    • Create cart conditions for time-based discounts or loyalty tiers:
      CartCondition::create([
          'name' => 'lunch_discount',
          'type' => 'percentage',
          'value' => 10,
          'applies_to' => 'menus',
          'conditions' => json_encode(['time' => '12:00-14:00']),
      ]);
      
  4. Checkout Customization:

    • Override the default checkout view:
      @extends('cart::checkout')
      @section('extra_fields')
          <div>{{ Form::text('custom_field', null, ['placeholder' => 'Special instructions']) }}</div>
      @endsection
      
  5. API Access:

    • Expose cart endpoints for mobile apps or third-party integrations:
      Route::middleware('auth:api')->group(function () {
          Route::get('/cart', [CartController::class, 'getCart']);
          Route::post('/cart/add', [CartController::class, 'addToCart']);
      });
      
  6. Testing:

    • Use the package’s built-in test helpers:
      $this->actingAs($user)
           ->post('/cart/add', ['menu_id' => 1, 'quantity' => 2])
           ->assertRedirect('/cart');
      

Gotchas and Tips

Pitfalls

  1. Session Key Conflicts:

    • If using multiple carts (e.g., for different locations or user roles), ensure unique CART_SESSION_KEY values in config:
      'session_key' => 'cart_' . env('APP_LOCATION_ID', 'default'),
      
    • Debug Tip: Check if cart items persist unexpectedly due to shared session keys.
  2. Stock Validation Bypass:

    • The out_of_stock_override feature can accidentally enable sales for unavailable items. Monitor the inventory_override_duration setting in the admin panel.
  3. Payment Gateway Fallbacks:

    • If no default payment gateway is set, the package falls back to Cash on Delivery (COD). Verify this behavior aligns with your business rules:
      $defaultGateway = \TastyIgniter\PayRegister\Facades\PaymentGateway::getDefault();
      
  4. Menu Option Validation:

    • Numeric menu options (e.g., quantity selectors) must be validated before adding to the cart. Use the validateOption() method or override the MenuOption model:
      public function validateOption($value, $menuOption)
      {
          if ($menuOption->type === 'number' && !is_numeric($value)) {
              throw new \InvalidArgumentException('Invalid quantity.');
          }
          return parent::validateOption($value, $menuOption);
      }
      
  5. Order Status Workflows:

    • Custom workflows require proper setup in the admin panel. Test transitions thoroughly to avoid orders getting stuck in unexpected states.
  6. Performance with Large Orders:

    • For high-order volumes, ensure database indexes are optimized (e.g., orders table indexes on status_id, created_at):
      Schema::table('orders', function (Blueprint $table) {
          $table->index('status_id');
          $table->index('created_at');
      });
      
  7. Blade Template Conflicts:

    • If using custom Blade views, ensure they extend the correct package views (e.g., @extends('cart::layouts.app')). Override templates in resources/views/vendor/cart/.

Debugging Tips

  1. Cart Contents:

    • Dump the cart contents for debugging:
      dd(\TastyIgniter\Cart\Facades\Cart::getContent());
      
  2. Order Events:

    • Listen for order events to debug workflows:
      Order::created(function ($order) {
          \Log::info('New order created:', ['order_id' => $order->id]);
      });
      
  3. Session Issues:

    • Clear the cart session manually if items persist unexpectedly:
      session()->forget(\TastyIgniter\Cart\Facades\Cart::getSessionKey());
      
  4. Inventory Logs:

    • Enable inventory logs to track stock changes:
      \TastyIgniter\Inventory\Facades\Inventory::enableLogging();
      
  5. Payment Gateway Errors:

    • Check the payment_gateways table for misconfigured gateways or missing API keys.

Extension Points

  1. Custom Cart Conditions:
    • Extend the CartCondition model to add logic (e.g., user-specific discounts):
      namespace App\Extensions;
      
      use TastyIgniter\Cart\Models\CartCondition;
      
      class LoyaltyDiscount extends CartCondition
      {
          public function apply($cart)
          {
              if (auth()->user()->isLoyaltyMember()) {
                  $cart->applyDiscount('loyalty_15_percent', 15);
              }
          }
      }
      
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