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

Products Stocks Laravel Package

baks-dev/products-stocks

Модуль складского учета продукции для PHP 8.4+. Установка через Composer, установка конфигурации и ресурсов командой baks:assets:install, миграции Doctrine для обновления схемы БД, тесты PHPUnit (group=products-stocks).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require baks-dev/products-stocks
    php bin/console baks:assets:install
    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
    • Verify the package is registered in config/app.php under providers.
  2. First Use Case: Check Stock Levels Inject the StockService into a controller or service:

    use BaksDev\ProductsStocks\Services\StockService;
    
    public function __construct(private StockService $stockService) {}
    
    public function checkStock(Request $request, Product $product) {
        $stock = $this->stockService->getStock($product->id);
        return response()->json(['stock' => $stock]);
    }
    
  3. Key Classes to Explore

    • StockService: Core service for stock operations.
    • StockRepository: Eloquent repository for stock records.
    • StockEvent: Event listeners for stock changes (e.g., StockUpdated).
    • StockMiddleware: Middleware for stock validation (if provided).

Implementation Patterns

Core Workflows

  1. Stock Management

    • Update Stock Levels:
      $this->stockService->updateStock($productId, $quantityChange, $userId);
      
    • Reserve Stock (for orders):
      $this->stockService->reserveStock($productId, $quantity, $orderId);
      
    • Release Reserved Stock:
      $this->stockService->releaseReservedStock($orderId);
      
  2. Integration with Product Module

    • Listen for ProductCreated/ProductUpdated events to initialize stock records:
      public function handle(ProductEvent $event) {
          $this->stockService->initializeStock($event->product);
      }
      
  3. API Endpoints

    • Example: /api/stock/{productId} (GET/PUT/PATCH for stock adjustments).
    • Use Laravel’s API resources to format responses:
      return new StockResource($this->stockService->getStock($productId));
      
  4. Batch Operations

    • Update stock for multiple products via a CSV import:
      $this->stockService->bulkUpdateStock($productIds, $quantities);
      

Best Practices

  • Transactions: Wrap stock updates in database transactions to avoid inconsistencies:
    DB::transaction(function () use ($productId, $quantity) {
        $this->stockService->updateStock($productId, $quantity);
        // Other related operations (e.g., order creation)
    });
    
  • Caching: Cache stock levels for frequently accessed products:
    Cache::remember("stock_{$productId}", now()->addHours(1), function () use ($productId) {
        return $this->stockService->getStock($productId);
    });
    
  • Events: Extend stock logic via events (e.g., StockLow, StockOutOfStock):
    event(new StockLow($productId, $threshold));
    

Gotchas and Tips

Pitfalls

  1. Race Conditions

    • Stock updates are not atomic by default. Use DB::transaction() or optimistic locking:
      $stock = Stock::where('product_id', $productId)->lockForUpdate()->first();
      
    • For high-traffic sites, consider Redis-based locking or a queue (e.g., Laravel Queues).
  2. Negative Stock

    • The package may not enforce negative stock prevention. Add validation:
      if ($newStock < 0) {
          throw new \InvalidArgumentException("Stock cannot be negative");
      }
      
  3. Migration Conflicts

    • If the package’s migrations conflict with existing ones, manually merge tables or use --force cautiously:
      php bin/console doctrine:migrations:migrate --force
      
  4. Locale/Translation Issues

    • The package may use Russian labels (e.g., "Остаток"). Override translations in resources/lang/en/products-stocks.php:
      return [
          'stock' => 'Inventory',
          'reserved' => 'Reserved',
      ];
      

Debugging Tips

  • Log Stock Changes: Add logging to StockService:
    \Log::info('Stock updated', [
        'product_id' => $productId,
        'change' => $quantityChange,
        'user_id' => $userId,
    ]);
    
  • Query Debugging: Enable Doctrine logging in .env:
    DOCTRINE_ORM_LOGGING=true
    
  • Test Coverage: Run group-specific tests:
    php bin/phpunit --group=products-stocks --filter=StockServiceTest
    

Extension Points

  1. Custom Stock Rules

    • Extend StockService to add business logic (e.g., minimum stock thresholds):
      class CustomStockService extends StockService {
          public function checkMinimumStock(Product $product, int $threshold) {
              $stock = $this->getStock($product->id);
              if ($stock < $threshold) {
                  event(new StockLow($product->id, $threshold));
              }
          }
      }
      
  2. Additional Stock Types

    • Add custom stock fields (e.g., damaged_stock) via a migration and extend the Stock model:
      public function getDamagedStockAttribute() {
          return $this->attributes['damaged_stock'] ?? 0;
      }
      
  3. Webhooks/Notifications

    • Subscribe to StockUpdated events to trigger webhooks or notifications:
      public function handle(StockUpdated $event) {
          Notification::route('mail', $event->user->email)
              ->notify(new StockAlert($event->product, $event->newStock));
      }
      
  4. Multi-Warehouse Support

    • Extend the Stock model to include warehouse_id and update queries:
      $stock = $this->stockService->getStock($productId, $warehouseId);
      
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver