If you need to add extra functionality to tags or override existing behavior, you can use a custom Eloquent model instead of the default Spatie\Tags\Tag.
To implement a custom tag model, follow these two steps in your model that uses the HasTags trait:
- Override
getTagClassName(): Return the fully qualified class name of your custom tag model. Your custom model must extend Spatie\Tags\Tag and use the same tags table. - Override
tags(): You must manually define the tags() relationship to ensure the package continues to use the tag_id column for the relationship instead of attempting to use a column named after your custom model (e.g., your_tag_model_id).
use Illuminate\Database\Eloquent\Model;
use Spatie\Tags\HasTags;
class YourModel extends Model
{
use HasTags;
public static function getTagClassName(): string
{
return YourTagModel::class;
}
}
// ... inside YourModel
public function tags(): MorphToMany
{
return $this
->morphToMany(self::getTagClassName(), 'taggable', 'taggables', null, 'tag_id')
->orderBy('order_column');
}