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

Taxonomy Laravel Package

sylius/taxonomy

Sylius Taxonomy component for building and managing product taxonomies in PHP. Provides models and utilities for taxons and hierarchical trees, supporting categorization, navigation menus, and structured browsing in Sylius-based eCommerce apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sylius/taxonomy
    

    Add to config/app.php under providers:

    Sylius\Component\Taxonomy\TaxonomyServiceProvider::class,
    

    Publish migrations (if using Doctrine):

    php artisan vendor:publish --provider="Sylius\Component\Taxonomy\TaxonomyServiceProvider" --tag="migrations"
    php artisan migrate
    
  2. First Use Case: Define a taxonomy (e.g., ProductCategory) and a root node:

    use Sylius\Component\Taxonomy\Model\TaxonInterface;
    use Sylius\Component\Taxonomy\Model\TaxonTranslationInterface;
    
    $taxon = new Taxon();
    $taxon->setCode('electronics');
    $taxon->setTranslation(new TaxonTranslation(), 'en_US');
    $taxon->getTranslation()->setName('Electronics');
    
    $taxonManager->persist($taxon);
    $taxonManager->flush();
    
  3. Where to Look First:

    • Entities: Sylius\Component\Taxonomy\Model\Taxon and TaxonTranslation.
    • Services: TaxonManager (CRUD), TaxonRepository (queries).
    • Doctrine Extensions: Gedmo\Sortable (for ordering).

Implementation Patterns

Workflows

  1. Hierarchical Taxonomy Management:

    // Create a child taxon under "electronics"
    $laptopTaxon = new Taxon();
    $laptopTaxon->setCode('laptops');
    $laptopTaxon->setParent($electronicsTaxon); // Link to parent
    $laptopTaxon->setTranslation(new TaxonTranslation(), 'en_US');
    $laptopTaxon->getTranslation()->setName('Laptops');
    $taxonManager->persist($laptopTaxon);
    
  2. Bulk Operations: Use TaxonRepository for batch queries:

    $children = $taxonRepository->findChildren($parentTaxon);
    $allDescendants = $taxonRepository->findDescendants($parentTaxon);
    
  3. Translation Handling: Dynamically load translations via TaxonTranslation:

    $taxon->addTranslation(new TaxonTranslation(), 'fr_FR');
    $taxon->getTranslation('fr_FR')->setName('Électronique');
    
  4. Integration with Eloquent: If using Eloquent, extend the Taxon model:

    class Taxon extends \Sylius\Component\Taxonomy\Model\Taxon implements \Illuminate\Database\Eloquent\Model
    {
        use \Sylius\Component\Taxonomy\Model\TaxonTrait;
        use \Illuminate\Database\Eloquent\Model;
    }
    

Common Use Cases

  • Product Categorization: Attach taxons to products via a many-to-many relationship:
    $product->taxons()->attach($electronicsTaxon);
    
  • Dynamic Navigation: Fetch a taxon’s path for breadcrumbs:
    $path = $taxonRepository->getPath($taxon);
    // Returns: ['electronics' => 'Electronics', 'laptops' => 'Laptops']
    
  • Filtering: Query products by taxon:
    $products = Product::whereHas('taxons', function ($query) use ($taxon) {
        $query->where('taxons.code', $taxon->getCode());
    })->get();
    

Gotchas and Tips

Pitfalls

  1. Circular References: Avoid creating loops in the hierarchy (e.g., A → B → A). The package doesn’t enforce this; validate manually:

    if ($taxonRepository->isDescendant($taxon, $parentTaxon)) {
        throw new \RuntimeException('Circular reference detected!');
    }
    
  2. Translation Locale Mismatches: Always set the locale when adding translations:

    // ❌ Bad: Missing locale
    $taxon->addTranslation(new TaxonTranslation());
    
    // ✅ Good
    $taxon->addTranslation(new TaxonTranslation(), 'en_US');
    
  3. Performance with Deep Hierarchies: Fetching all descendants of a deep taxon can be slow. Use DISTINCT in queries or limit depth:

    $taxonRepository->findDescendants($taxon, 2); // Max depth = 2
    
  4. Doctrine vs. Eloquent:

    • Doctrine: Uses Sylius\Component\Taxonomy\Repository\Doctrine\TaxonRepository.
    • Eloquent: Requires custom implementation for findChildren/findDescendants.

Debugging

  • Missing Taxons: Ensure TaxonManager is bound in the container and migrations are run.
    php artisan db:show
    
  • Translation Issues: Check if the locale is supported in TaxonTranslation:
    $taxon->getTranslation('en_US')->getName(); // Returns null if missing
    

Extension Points

  1. Custom Taxon Fields: Extend Taxon to add attributes (e.g., icon, slug):

    class ExtendedTaxon extends Taxon
    {
        protected $icon;
        protected $slug;
    
        // Add getters/setters and update migrations.
    }
    
  2. Event Listeners: Hook into taxon events (e.g., prePersist, postRemove) via Symfony events:

    $dispatcher->addListener(TaxonEvents::PRE_PERSIST, function (TaxonEvent $event) {
        $taxon = $event->getSubject();
        // Validate or modify $taxon here.
    });
    
  3. Custom Repository Methods: Add query methods to TaxonRepository:

    public function findByPath(array $path)
    {
        return $this->createQueryBuilder('t')
            ->where('t.code = :code')
            ->setParameter('code', end($path))
            ->andWhere('t.parent IN (
                SELECT parent FROM SyliusTaxonomyTaxon t2
                WHERE t2.code IN (:codes)
            )')
            ->setParameter('codes', $path)
            ->getQuery()
            ->getOneOrNullResult();
    }
    
  4. Soft Deletes: Enable soft deletes by adding use SoftDeletableTrait to Taxon and updating the entity:

    class Taxon extends \Sylius\Component\Taxonomy\Model\Taxon
    {
        use \Sylius\Component\Taxonomy\Model\TaxonTrait;
        use \Doctrine\ORM\Mapping as ORM;
        use \Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
    
        // Add @ORM\SoftDeleteable field.
    }
    

Configuration Quirks

  • Default Locale: Set in config/packages/sylius_taxonomy.yaml:
    sylius_taxonomy:
        default_locale: en_US
    
  • Tree Ordering: Use Gedmo\Sortable for manual ordering:
    # config/packages/gedmo_sortable.yaml
    gedmo_sortable:
        sortable: true
    
    Then update the Taxon entity:
    use Gedmo\Sortable\Mapping\Annotation as Gedmo;
    
    /**
     * @Gedmo\Sortable
     */
    protected $position;
    
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
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