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

Shopwire Laravel Package

nickdekruijk/shopwire

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require nickdekruijk/shopwire
    php artisan vendor:publish --tag=config --provider="NickDeKruijk\Shopwire\ShopwireServiceProvider"
    
  2. Configure Product Model Add the ShopwireProduct trait to your Product model:

    use NickDeKruijk\Shopwire\Traits\ShopwireProduct;
    class Product extends Model { use ShopwireProduct; }
    
  3. Run Migrations

    php artisan migrate
    
  4. Basic Livewire Integration Create a Livewire component for the cart:

    php artisan make:livewire Cart
    

    Use the Shopwire facade or inject the Cart service into your component:

    use NickDeKruijk\Shopwire\Facades\Shopwire;
    // or
    public $cart;
    public function mount() { $this->cart = Shopwire::cart(); }
    
  5. First Use Case: Add to Cart In a Livewire component or controller, add a product to the cart:

    Shopwire::cart()->add($product, $quantity = 1);
    

Implementation Patterns

Core Workflows

  1. Cart Management

    • Add/Update Items:
      Shopwire::cart()->add($product, $quantity);
      Shopwire::cart()->update($productId, $quantity);
      
    • Remove Items:
      Shopwire::cart()->remove($productId);
      
    • Clear Cart:
      Shopwire::cart()->clear();
      
  2. Checkout Flow

    • Validate Cart (e.g., stock, minimum order):
      if (Shopwire::cart()->isValid()) {
          // Proceed to checkout
      }
      
    • Process Payment (integrate with Stripe/PayPal):
      $paymentIntent = Shopwire::checkout()->process($cartItems, $total);
      
  3. Livewire Integration

    • Sync Cart State: Use Livewire's updated() or render() to reflect cart changes in the UI:
      public function updatedCart() {
          $this->cart = Shopwire::cart()->get();
      }
      
    • Real-Time Updates: Trigger Livewire events when cart changes occur (e.g., cart-updated):
      Shopwire::cart()->add($product);
      $this->emit('cart-updated');
      
  4. Product-Specific Logic

    • Dynamic Pricing: Override getPrice() in your Product model to apply discounts:
      public function getPriceAttribute() {
          return $this->base_price - $this->discount;
      }
      
    • Inventory Checks: Use the checkStock() method to validate availability:
      if (Shopwire::cart()->checkStock()) {
          // Proceed
      }
      

Integration Tips

  1. Session-Based Cart By default, the cart persists in the session. For guest users, ensure session drivers (e.g., file, database) are configured in .env:

    SESSION_DRIVER=database
    
  2. Customizing Cart Storage Extend the Cart class to use a different storage backend (e.g., Redis):

    // app/Providers/AppServiceProvider.php
    Shopwire::extend(function ($app) {
        $app->singleton(\NickDeKruijk\Shopwire\Contracts\Cart::class, function () {
            return new \App\Services\RedisCart();
        });
    });
    
  3. Localization Use the setLocale() method to support multi-language pricing/currency:

    Shopwire::cart()->setLocale('en_US');
    
  4. Testing Mock the Cart service in tests:

    $this->app->instance(\NickDeKruijk\Shopwire\Contracts\Cart::class, MockCart::class);
    

Gotchas and Tips

Pitfalls

  1. Model Configuration

    • Error: Class 'App\Models\Product' does not use ShopwireProduct trait. Fix: Ensure the trait is added to your Product model before running migrations. The package creates a shopwire_products table that expects the trait’s methods.
  2. Session Cart Persistence

    • Issue: Cart items disappear after page refresh for guest users. Fix: Verify SESSION_DRIVER is set to database or redis in .env. For API-based carts, use a cookie-based solution or database-backed storage.
  3. Livewire Event Conflicts

    • Problem: Cart updates don’t trigger UI refreshes. Solution: Explicitly emit Livewire events after cart modifications:
      Shopwire::cart()->add($product);
      $this->emit('cart-updated');
      
      Ensure your Livewire component listens to this event:
      protected $listeners = ['cart-updated' => 'render'];
      
  4. Quantity Validation

    • Gotcha: The package doesn’t enforce max/min quantities by default. Workaround: Add validation in your Livewire component:
      public function addToCart($product, $quantity = 1) {
          $maxQuantity = $product->stock;
          $quantity = max(1, min($quantity, $maxQuantity));
          Shopwire::cart()->add($product, $quantity);
      }
      
  5. Migration Conflicts

    • Error: Table 'shopwire_products' already exists. Fix: If you’ve modified the shopwire_products table manually, reset it:
      php artisan migrate:fresh --env=testing
      
      Or manually drop the table before re-running migrations.

Debugging Tips

  1. Log Cart State Dump the cart contents for debugging:

    \Log::info('Cart contents:', ['items' => Shopwire::cart()->get()->items]);
    
  2. Check Config Values Validate the config/shopwire.php file for custom model/class names:

    'model' => App\Models\Product::class,
    'currency' => 'USD',
    
  3. Livewire Wire:ignore If cart items flicker during updates, add wire:ignore to the cart container in Blade:

    <div wire:ignore>
        @foreach (Shopwire::cart()->get()->items as $item)
            {{ $item->name }} - {{ $item->quantity }}
        @endforeach
    </div>
    

Extension Points

  1. Custom Cart Rules Extend the Cart class to add business logic (e.g., bulk discounts):

    // app/Services/CustomCart.php
    namespace App\Services;
    use NickDeKruijk\Shopwire\Cart as BaseCart;
    
    class CustomCart extends BaseCart {
        public function applyBulkDiscount() {
            if ($this->total() > 1000) {
                $this->setDiscount(100);
            }
        }
    }
    

    Bind it in AppServiceProvider:

    Shopwire::extend(function ($app) {
        $app->singleton(\NickDeKruijk\Shopwire\Contracts\Cart::class, function () {
            return new \App\Services\CustomCart();
        });
    });
    
  2. Override Checkout Logic Replace the default checkout handler:

    Shopwire::extendCheckout(function ($app) {
        return new \App\Services\CustomCheckout();
    });
    
  3. Add Custom Fields to Cart Items Extend the ShopwireProduct trait to include additional attributes:

    // app/Models/Product.php
    use NickDeKruijk\Shopwire\Traits\ShopwireProduct;
    
    class Product extends Model {
        use ShopwireProduct;
    
        public function getCustomAttribute() {
            return $this->attributes['custom_field'];
        }
    }
    

    Update the shopwire_products table migration to include custom_field.

  4. Webhook Integration Listen for cart events (e.g., cart.item.added) via Livewire or Laravel events:

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        \NickDeKruijk\Shopwire\Events\ItemAdded::class => [
            \App\Listeners\LogCartActivity::class,
        ],
    ];
    
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