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

Materials Stocks Laravel Package

baks-dev/materials-stocks

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require baks-dev/materials-stocks
    

    Ensure your Laravel project meets the PHP 8.4+ requirement and has baks-dev/core (≥7.4) installed.

  2. Publish Config & Migrations

    php artisan vendor:publish --provider="BaksDev\MaterialsStocks\MaterialsStocksServiceProvider" --tag="config"
    php artisan vendor:publish --provider="BaksDev\MaterialsStocks\MaterialsStocksServiceProvider" --tag="migrations"
    

    Run migrations:

    php artisan migrate
    
  3. First Use Case: Register a Material

    use BaksDev\MaterialsStocks\Facades\MaterialsStocks;
    
    // Register a new material type (e.g., "Wood")
    MaterialsStocks::material()->create([
        'name' => 'Wood',
        'code' => 'WD',
        'unit' => 'kg',
    ]);
    
  4. Key Facades

    • MaterialsStocks::material() → Material CRUD
    • MaterialsStocks::stock() → Stock movement operations
    • MaterialsStocks::report() → Generate stock reports

Implementation Patterns

Core Workflows

1. Material Management

  • Create/Update Materials
    $material = MaterialsStocks::material()->create([
        'name' => 'Steel',
        'code' => 'ST',
        'unit' => 'ton',
        'description' => 'Carbon steel',
    ]);
    
  • Bulk Import via CSV Use the import method with a SplFileInfo object:
    $file = new SplFileInfo(storage_path('app/materials.csv'));
    MaterialsStocks::material()->import($file);
    

2. Stock Operations

  • Record Incoming Stock
    MaterialsStocks::stock()->incoming([
        'material_id' => 1, // Wood
        'quantity' => 500,
        'unit_cost' => 10.50,
        'source' => 'Supplier X',
        'notes' => 'Delivery #123',
    ]);
    
  • Record Outgoing Stock
    MaterialsStocks::stock()->outgoing([
        'material_id' => 1,
        'quantity' => 100,
        'destination' => 'Production Line A',
        'reference_id' => 42, // Related order ID
    ]);
    
  • Adjust Stock Manually
    MaterialsStocks::stock()->adjust([
        'material_id' => 1,
        'quantity' => -50, // Negative for deductions
        'reason' => 'Wastage',
    ]);
    

3. Reporting

  • Generate Stock Report
    $report = MaterialsStocks::report()->getStockReport(
        materialIds: [1, 2], // Optional filter
        startDate: now()->subMonth(),
        endDate: now()
    );
    
  • Export to Excel
    $report = MaterialsStocks::report()->getStockReport();
    return Excel::download(new StockReportExport($report), 'stock_report.xlsx');
    

4. Integration with Core BaksDev

  • Event Listeners Subscribe to stock events (e.g., StockCreated) in your EventServiceProvider:
    protected $listen = [
        \BaksDev\MaterialsStocks\Events\StockCreated::class => [
            \App\Listeners\UpdateInventory::class,
        ],
    ];
    
  • API Resources Extend the default API responses:
    use BaksDev\MaterialsStocks\Http\Resources\MaterialResource;
    
    class CustomMaterialResource extends MaterialResource {
        public function toArray($request) {
            $array = parent::toArray($request);
            $array['custom_field'] = 'value';
            return $array;
        }
    }
    

Advanced Patterns

Custom Validation Rules

Extend the default validator by creating a custom rule:

use BaksDev\MaterialsStocks\Rules\MaterialRule;

class CustomMaterialRule extends MaterialRule {
    public function passes($attribute, $value) {
        // Add custom logic (e.g., check against another table)
        return parent::passes($attribute, $value);
    }
}

Stock Movement Policies

Override default stock behavior (e.g., enforce minimum stock levels):

use BaksDev\MaterialsStocks\Contracts\StockPolicy;

class MinimumStockPolicy implements StockPolicy {
    public function beforeOutgoing($material, $quantity) {
        if ($material->current_stock - $quantity < 100) {
            throw new \Exception("Minimum stock level violated!");
        }
    }
}

Register the policy in config/materials-stocks.php:

'policies' => [
    \App\Policies\MinimumStockPolicy::class,
],

Multi-Warehouse Support

Use the warehouse_id field in stock operations:

MaterialsStocks::stock()->incoming([
    'material_id' => 1,
    'warehouse_id' => 2, // Secondary warehouse
    'quantity' => 200,
]);

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatch

    • The package requires PHP 8.4+. Ensure your php.ini and Laravel environment match.
    • Fix: Update your PHP version or check for a compatible fork.
  2. Missing Core Dependency

    • baks-dev/core (≥7.4) is mandatory. Install it first:
      composer require baks-dev/core:^7.4
      
    • Error: Class 'BaksDev\Core\BaseModel' not found → Verify baks-dev/core is loaded in config/app.php under providers.
  3. Migration Conflicts

    • If you’ve customized the materials or stocks tables, merge migrations manually before running:
      php artisan migrate --step
      
    • Tip: Use php artisan vendor:publish --tag=migrations to inspect the raw migration files first.
  4. Facade Not Found

    • Ensure the service provider is registered in config/app.php:
      BaksDev\MaterialsStocks\MaterialsStocksServiceProvider::class,
      
    • Debug: Run php artisan package:discover to refresh providers.
  5. Stock Quantity Precision

    • The package uses floating-point arithmetic for quantities. For exact calculations (e.g., financial reports), cast to string or use bcmath:
      $total = (string) $stock->quantity * (float) $stock->unit_cost;
      

Debugging Tips

  1. Enable Query Logging Add to AppServiceProvider:

    public function boot() {
        if (app()->environment('local')) {
            \DB::enableQueryLog();
        }
    }
    

    Check logs after stock operations:

    dd(\DB::getQueryLog());
    
  2. Test Stock Events Use the listeners config to log events:

    'events' => [
        'StockCreated' => \App\Listeners\LogStockEvent::class,
    ],
    
  3. Validate Material Codes The code field is unique. Use:

    MaterialsStocks::material()->updateOrCreate(
        ['code' => 'WD'],
        ['name' => 'Wood Updated']
    );
    

Extension Points

  1. Custom Material Attributes Extend the Material model:

    use BaksDev\MaterialsStocks\Models\Material;
    
    class CustomMaterial extends Material {
        protected $casts = [
            'is_perishable' => 'boolean',
        ];
    }
    

    Update the config to use your model:

    'models' => [
        'material' => \App\Models\CustomMaterial::class,
    ],
    
  2. Stock Movement Notifications Publish the event listener template:

    php artisan vendor:publish --tag=materials-stocks-events
    

    Extend the default listener:

    class CustomStockListener {
        public function handle(StockCreated $event) {
            // Send Slack/Email notification
        }
    }
    
  3. API Rate Limiting Add middleware to the StockController:

    Route::middleware(['throttle:10,1'])->group(function () {
        Route::apiResource('stocks', \BaksDev\MaterialsStocks\Http\Controllers\StockController::class);
    });
    
  4. Localization Override translations:

    php artisan vendor:publish --tag=materials-stocks-lang
    
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
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
spatie/mailcoach-vapor