Add tags and categories to any model with Laraterms

2026年8月6日2 次浏览来源:Dev.to阅读原文

Sometimes you need tags on a model.

The usual answer is a table, a pivot, a slug and a , 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.

Step 1: define a taxonomy A taxonomy is a kind of label, declared in .

Start with a flat taxonomy; the file already ships one you can keep.

Step 2: tag a model Add the 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.

Filtering by tag is a query scope, so it composes with the rest of your query.

Hierarchical categories Set on a taxonomy and its terms form a tree.

Read the whole tree in one query, and walk a term's ancestry.

The above is enforced: attaching a second category throws a instead of quietly allowing two.

Keeping tenants apart The in each taxonomy means terms are isolated per tenant, which is the feature you would otherwise hand-roll with an on every query.

Tell Laraterms how to find a model's tenant once, in a service provider.

Now a tag created in one organization is invisible to another, and the same label in two organizations is two separate terms.

For taxonomies that really are shared across everyone, like languages, set instead.

Wrapping up That is tags, categories and tenant isolation without a single pivot table of your own: a config entry per taxonomy, the trait, and attach and query calls.

It also does translations and cross-locale search on the same two tables when you need them. 👉 Package on Packagist: https://packagist.org/packages/edulazaro/laraterms 👉 Source on GitHub: https://github.com/edulazaro/laraterms

分享
Baike.dev

baike.dev helps you discover great languages, frameworks, databases, DevOps and cloud-native tools.

Quick links

About

Contribute

Found a great developer tool? Share it with the community.

Submit a tool
© 2026 baike.dev Developer EncyclopediaUpdated daily · Discover great developer tools