Adding tags on entities

Tag Module


1. Add interface & trait on desired entity

Your entity needs to implement the Modules\Tag\Contracts\TaggableInterface interface.

In order for your entity to satisfy this interface it needs to use the following traits:

  • Modules\Core\Traits\NamespacedEntity
  • Modules\Tag\Traits\TaggableTrait

Tags are organised by namespace. This is used in order to get the tags for a specific namespace on the display of the field. It also creates tags for that namespace if tags need to be created.

By default the TaggableTrait will use the full namespace of your entity. However, you can specify a nicer / shorter namespace to use by using the static $entityNamespace property on your entity.

Example:

protected static $entityNamespace = 'asgardcms/media';

2. Defining a new namespace to use for tags

In your module Service Provider, boot() method, you now need to add the namespace it's going to use. This can be done using the TagManager interface.

$this->app[TagManager::class]->registerNamespace(new File());

And with this, the Tag Module is aware of the new namespace.

3. Display the tag field on your views

By using a custom blade directive you can include the tags field on your views.

  • The first argument is the namespace to get the tags for.
  • (optional) Second argument is the entity to fetch the tags for (pre-filling the input if tags are present for given entity).
  • (optional) Third argument can be a view to use. This will override the default tags view with its input field.
  • (optional) Fourth and last argument can be a name to use. This will override the default name for the input field.
@tags('asgardcms/media', $file)

4. Store tags

In your repositories you need to call the setTags() method to persist the tags on your entity.

$file->setTags(array_get($data, 'tags'));

And that's all on how to use tags for your entities.

(optional) Removing morph relationship on delete of entity

When you delete the entity to which there are tags linked to, you might want to delete the relation between your entity and the tags (the morph relationship). This relationship can be viewed in the tag__tagged table.

To delete this link when deleting your entity, you can call the following method in your repository, for instance the destroy method:

public function destroy($page)
{
    $page->untag();

    event(new PageWasDeleted($page));

    return $page->delete();
}

When the untag() methods gets no argument, it will remove all links for the entity.

Mobile Analytics