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

Laravel Category Module Laravel Package

zxf5115/laravel-category-module

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require zxf5115/laravel-category-module
    php artisan vendor:publish --provider="Zxf5115\CategoryModule\CategoryServiceProvider" --tag="config"
    php artisan migrate
    
    • Publishes config (config/category.php) and runs migrations for the categories table.
  2. Basic Usage

    • Create a category:
      use Zxf5115\CategoryModule\Models\Category;
      
      $category = Category::create([
          'name' => 'Electronics',
          'parent_id' => null, // Root category
          'slug' => 'electronics',
          'description' => 'All electronics products',
          'status' => 1, // Active
      ]);
      
    • Fetch categories (tree structure):
      $categories = Category::with('children')->where('parent_id', null)->get();
      
    • Helper methods:
      // Get all categories as a nested array
      $tree = Category::getTree();
      
      // Check if a category exists
      Category::hasSlug('electronics');
      
  3. First Use Case

    • E-commerce product categorization:
      // Attach a product to a category
      $product->categories()->attach($category->id);
      

Implementation Patterns

Common Workflows

  1. Hierarchical Data Handling

    • Recursive tree traversal (e.g., for breadcrumbs or dropdowns):
      $path = [];
      $category->getPath($path); // Fills $path with [root, parent, current]
      
    • Depth-limited queries:
      $categories = Category::where('depth', '<=', 2)->get();
      
  2. API/Controller Integration

    • Resource Controller:
      use Zxf5115\CategoryModule\Http\Controllers\CategoryController;
      
      // Extend or override methods in `app/Http/Controllers/CategoryController.php`
      
    • API Responses:
      return CategoryResource::collection($categories)->additional([
          'meta' => ['count' => $categories->count()]
      ]);
      
  3. Middleware for Category Access

    • Restrict routes to specific categories:
      Route::middleware(['category.access:electronics'])->group(function () {
          // Only accessible if user has permission for 'electronics' category
      });
      
  4. Event-Driven Extensions

    • Listen for category creation/deletion:
      Category::created(function ($category) {
          // Sync with external services (e.g., Elasticsearch)
      });
      

Integration Tips

  • Polymorphic Relationships: Extend the categories table to support many-to-many with other models (e.g., products, posts):
    // In a Product model:
    public function categories()
    {
        return $this->morphToMany(Category::class, 'categorizable');
    }
    
  • Caching: Cache the category tree for performance:
    $tree = Cache::remember('category.tree', now()->addHours(1), function () {
        return Category::getTree();
    });
    
  • Validation: Use the package’s built-in rules:
    use Zxf5115\CategoryModule\Rules\UniqueSlug;
    
    $request->validate([
        'slug' => ['required', new UniqueSlug],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Slug Conflicts

    • The package enforces unique slugs. If you manually update a slug, ensure it doesn’t conflict:
      // Avoid:
      Category::where('slug', 'old-slug')->update(['slug' => 'new-slug']);
      // Use:
      $category->update(['slug' => 'new-slug']); // Handles uniqueness internally
      
  2. Depth Calculation

    • The depth column is auto-updated via observers. If you bypass the model (e.g., raw SQL), depth may become stale:
      -- ❌ Avoid direct inserts/updates without model methods
      DB::table('categories')->insert([...]);
      
  3. Parent-Child Loops

    • Circular references (e.g., A → B → A) will break the tree structure. Validate parent IDs:
      $request->validate([
          'parent_id' => ['nullable', 'exists:categories,id', 'not_in:' . $category->id],
      ]);
      
  4. Migration Conflicts

    • If you customize the categories table, ensure the package’s migrations don’t overwrite your changes. Publish and modify the migration:
      php artisan vendor:publish --tag="migrations"
      

Debugging

  • Tree Structure Issues:
    • Check the parent_id and depth columns directly in the DB. Use:
      Category::toTree(); // Debug output
      
  • Observer Conflicts:
    • If created/updated observers fire unexpectedly, disable them temporarily:
      Category::observe([]); // Disable all observers
      

Extension Points

  1. Custom Fields

    • Add columns to the categories table and extend the model:
      // In app/Models/Category.php
      protected $casts = [
          'is_featured' => 'boolean',
      ];
      
    • Update the migration and seeder accordingly.
  2. Custom Tree Methods

    • Override or add methods to the Category model:
      public function getFlatList()
      {
          return $this->where('parent_id', null)->with('children')->get()->flatten();
      }
      
  3. API Resources

    • Extend the default CategoryResource:
      namespace App\Http\Resources;
      
      use Zxf5115\CategoryModule\Http\Resources\CategoryResource as BaseResource;
      
      class CategoryResource extends BaseResource
      {
          public function toArray($request)
          {
              $array = parent::toArray($request);
              $array['custom_field'] = $this->custom_field;
              return $array;
          }
      }
      
  4. Service Provider Hooks

    • Bind custom implementations in AppServiceProvider:
      $this->app->bind(
          \Zxf5115\CategoryModule\Contracts\CategoryRepository::class,
          \App\Repositories\CustomCategoryRepository::class
      );
      

Config Quirks

  • Default Values: The config file (config/category.php) sets defaults like:

    'default_status' => 1, // Active by default
    'slug_generate_pattern' => 'slug-{random}',
    

    Override these to change behavior (e.g., disable auto-slug generation).

  • Soft Deletes: Enable soft deletes in the config:

    'soft_deletes' => true,
    

    Then use:

    $category->delete(); // Soft deletes instead of hard delete
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle