/laravel-taxonomies

Taxonomies and terms for Laravel

Primary LanguagePHPMIT LicenseMIT

Taxonomies and terms for Laravel

Basic package to categorize models by taxonomies and terms similar to wordpress

Tests

Features

  • Polymorphic, you can categorize all your models
  • Support for virtual many-to-one relationships to make your models only have one term per taxonomy
  • Terms nestable with parent-child relationship

Installation

You can install the package via composer:

composer require rosendito/laravel-taxonomies

Publish and run the migrations:

php artisan vendor:publish --provider="Rosendito\Taxonomies\TaxonomiesServiceProvider" --tag="migrations"
php artisan migrate

Basic usage

Make your model taggable adding the HasTaxonomies trait:

use Rosendito\Taxonomies\HasTaxonomies;

class Post extends model
{
    use HasTaxonomies;

    ...
}

Create some taxonomies and terms:

// database\seeders\CategoriesSeeder.php

use Rosendito\Taxonomies\Taxonomy;
use Rosendito\Taxonomies\Term;

$taxonomy = Taxonomy::create([
    'name' => 'Category'
]);

$term = Term::create([
    'taxonomy_id' => $taxonomy->id,
    'name' => 'Packages'
]);

Add terms to model:

$post = $this->addTerm('Category', 'Packages');

// You can pass the taxonomy and term as name, id or model
$term1 = Term::first();
$term2 = Term::latest()->first();

$post->addTerms('Category', [$term1->id, $term2]);

Query your models by term:

$posts = Post::hasTerm('Category', 'Packages')->get();

Resources