今日已更新 286 条资讯 | 累计 28598 条内容
关于我们

Add tags and categories to any model with Laraterms

Eduardo Lázaro 2026年08月06日 08:28 1 次阅读 来源:Dev.to

Sometimes you need tags on a model. The usual answer is a tags table, a pivot, a slug and a belongsToMany , and you write it again in the next project with slightly different columns. Laraterms replaces that with a config entry and a trait, and it comes with the parts you normally bolt on later: hierarchy, per-tenant isolation and translations. This is the simple path first, then the two features you reach for next. How to install One package, its config and two migrations. composer require edulazaro/laraterms php artisan vendor:publish --tag = laraterms-config php artisan vendor:publish --tag = laraterms-migrations php artisan migrate Step 1: define a taxonomy A taxonomy is a kind of label, declared in config/laraterms.php . Start with a flat tags taxonomy; the file already ships one you can keep. 'taxonomies' => [ 'tags' => [ 'hierarchical' => false , 'max_terms_per_model' => null , 'scope' => 'tenant' , ], ], Step 2: tag a model Add the HasTerms trait and the model can hold terms. Attaching is find-or-create: pass a label, and the term is created the first time and reused afterwards. use EduLazaro\Laraterms\Concerns\HasTerms ; class Post extends Model { use HasTerms ; } $post -> attachTerm ( 'Laravel' , 'tags' ); $post -> attachTerms ([ 'Laravel' , 'PHP' ], 'tags' ); $post -> syncTerms ([ 'Laravel' , 'Vue' ], 'tags' ); // replace the tag set $post -> termsIn ( 'tags' ); // read them back Filtering by tag is a query scope, so it composes with the rest of your query. Post :: whereHasTerm ( 'laravel' , 'tags' ) -> get (); Post :: whereHasAllTerms ([ 'laravel' , 'tutorial' ], 'tags' ) -> get (); Hierarchical categories Set hierarchical => true on a taxonomy and its terms form a tree. Read the whole tree in one query, and walk a term's ancestry. 'categories' => [ 'hierarchical' => true , 'max_terms_per_model' => 1 , 'scope' => 'tenant' , ], use EduLazaro\Laraterms\Support\TermTree ; $tree = TermTree :: for ( 'categories' ); // roots with children, one query $term -> b

本文内容来源于互联网,版权归原作者所有
查看原文