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 Category Laravel Package

baks-dev/materials-category

Laravel/PHP модуль «Materials Category» для каталога сырья: управление категориями и структурами материалов, интеграция с baks-dev/materials-catalog. Установка через Composer, тесты PHPUnit (group=materials-category). PHP 8.4+. MIT лицензия.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies

    composer require baks-dev/materials-category baks-dev/materials-catalog
    

    Note: Requires PHP 8.4+ and Laravel 10+ (or Symfony 6+).

  2. Publish Config & Migrations

    php artisan vendor:publish --provider="BaksDev\MaterialsCategory\MaterialsCategoryServiceProvider"
    php artisan migrate
    

    Verify: Check database/migrations/ for materials_categories and materials_category_materials tables.

  3. First Use Case: Create a Category

    use BaksDev\MaterialsCategory\Models\Category;
    
    $steel = Category::create([
        'name' => 'Steel',
        'slug' => 'steel',
        'parent_id' => null, // Root category
        'description' => 'Ferrous metal alloys',
    ]);
    
    $alloy = Category::create([
        'name' => 'Alloy',
        'slug' => 'alloy',
        'parent_id' => $steel->id,
    ]);
    
  4. Attach to a Material (via materials-catalog)

    use BaksDev\MaterialsCatalog\Models\Material;
    
    $material = Material::create([...]);
    $material->categories()->attach($alloy->id);
    

Where to Look First

  • Models: app/Models/BaksDev/MaterialsCategory/Models/ (e.g., Category.php).
  • Service Layer: src/Service/ for business logic (e.g., hierarchy validation).
  • Tests: tests/Feature/MaterialsCategory/ for workflow examples.
  • Config: config/materials-category.php (e.g., default hierarchy depth).

Implementation Patterns

Core Workflows

1. Hierarchical CRUD

// Create nested categories
$category = Category::create([
    'name' => 'Plastics',
    'slug' => 'plastics',
    'parent_id' => null,
]);

$pet = Category::create([
    'name' => 'PET',
    'slug' => 'pet',
    'parent_id' => $category->id,
]);

// Validate hierarchy (e.g., prevent loops)
if ($pet->isValidHierarchy()) {
    $pet->save();
}

2. Bulk Imports

use BaksDev\MaterialsCategory\Services\CategoryImporter;

$importer = new CategoryImporter();
$results = $importer->importFromCsv(
    'path/to/materials.csv',
    ['name', 'slug', 'parent_slug'] // Map CSV columns to model fields
);

3. Material-Category Linking

// Via materials-catalog
$material = Material::find(1);
$material->categories()->sync([$pet->id, $alloy->id]); // Attach/detach

4. Querying Hierarchies

// Get all children (recursive)
$children = $steel->children()->with('children')->get();

// Check if a material belongs to a category
if ($material->categories->contains($alloy)) {
    // Logic for alloy-specific pricing/rules
}

Integration Tips

Laravel-Symfony Bridge

  • Service Container: Wrap Symfony services in Laravel bindings:
    $this->app->bind(
        \BaksDev\MaterialsCategory\Service\CategoryValidator::class,
        \App\Services\LaravelCategoryValidator::class
    );
    
  • Validator: Replace Symfony’s Validator with Laravel’s:
    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make($data, [
        'name' => 'required|string|max:255',
        'slug' => 'required|unique:materials_categories',
    ]);
    

API/CLI Patterns

  • API Resources: Extend BaksDev\MaterialsCategory\Http\Resources\CategoryResource:
    namespace App\Http\Resources;
    
    use Illuminate\Http\Resources\Json\JsonResource;
    
    class CustomCategoryResource extends JsonResource {
        public function toArray($request) {
            return [
                'id' => $this->id,
                'name' => $this->name,
                'material_count' => $this->materials()->count(),
            ];
        }
    }
    
  • Commands: Create artisan commands for bulk operations:
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use BaksDev\MaterialsCategory\Models\Category;
    
    class SyncCategoriesCommand extends Command {
        protected $signature = 'materials:sync-categories';
        public function handle() {
            // Custom logic to sync with external API
            Category::syncExternalData();
        }
    }
    

UI Integration

  • Filament Admin Panel:
    use Filament\Forms;
    use BaksDev\MaterialsCategory\Models\Category;
    
    Filament::registerFormComponents([
        Forms\Components\Select::make('parent_id')
            ->relationship('parent', 'name')
            ->nullable(),
    ]);
    
  • Livewire Components:
    namespace App\Http\Livewire;
    
    use Livewire\Component;
    use BaksDev\MaterialsCategory\Models\Category;
    
    class CategoryManager extends Component {
        public $categories;
        public $newCategory = '';
    
        public function mount() {
            $this->categories = Category::with('children')->get();
        }
    
        public function addCategory() {
            Category::create(['name' => $this->newCategory]);
            $this->newCategory = '';
        }
    
        public function render() {
            return view('livewire.category-manager');
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Symfony Dependencies

    • Issue: The package uses Symfony’s Validator, Container, and EventDispatcher.
    • Fix: Create Laravel facades or abstract interfaces:
      // app/Providers/AppServiceProvider.php
      public function register() {
          $this->app->singleton(
              \Symfony\Component\Validator\Validator\ValidatorInterface::class,
              fn() => \Illuminate\Support\Facades\Validator::make([], [])
          );
      }
      
  2. Hierarchy Validation

    • Issue: Circular references (e.g., A → B → A) may crash.
    • Fix: Use the built-in isValidHierarchy() method or add a database constraint:
      Schema::table('materials_categories', function (Blueprint $table) {
          $table->foreign('parent_id')
                ->references('id')
                ->on('materials_categories')
                ->onDelete('restrict');
      });
      
  3. Missing Localization

    • Issue: Hardcoded Russian labels in models/views.
    • Fix: Override translations or add a localized_name column:
      $category->translate('en')->name = 'Steel';
      $category->translate('ru')->name = 'Сталь';
      
  4. Performance with Deep Trees

    • Issue: with('children') queries can be slow for 10+ levels.
    • Fix: Use materialized paths or closure tables:
      // Add to Category model
      protected $with = ['path'];
      
  5. Undocumented Events

    • Issue: No Laravel events (e.g., CategoryCreated) are fired.
    • Fix: Listen to Symfony events and dispatch Laravel events:
      // In a service provider
      $dispatcher->addListener(
          \BaksDev\MaterialsCategory\Event\CategoryCreatedEvent::class,
          fn($event) => event(new \App\Events\LaravelCategoryCreated($event->category))
      );
      

Debugging Tips

  • Enable Query Logging:
    \DB::enableQueryLog();
    $category = Category::with('children')->find(1);
    dd(\DB::getQueryLog());
    
  • Check for Symfony Exceptions: Wrap calls in try-catch:
    try {
        $validator = $this->app->get(\Symfony\Component\Validator\ValidatorInterface::class);
    } catch (\Exception $e) {
        // Fallback to Laravel validator
    }
    
  • Test Hierarchy Integrity:
    $category = Category::find(1);
    if (!$category->isValidHierarchy()) {
        throw new \Exception('Hierarchy loop detected!');
    }
    

Extension Points

  1. Custom Validation Rules

    // app/Rules/CustomCategoryRule.php
    use Illuminate\Contracts\Validation\Rule;
    
    class CustomCategoryRule implements Rule {
        public function passes($attribute, $value) {
            return str_contains($value, 'steel') || str_contains($value, 'alloy');
        }
        public function message() {
            return 'Category must include "steel" or "alloy".';
        }
    }
    

    Usage:

    $validator = Validator::make($data, [
        'name' => ['required', new CustomCategoryRule],
    ]);
    
  2. **Add Custom

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