To make an Eloquent model taggable just add the \Spatie\Tags\HasTags
trait to it:
use Illuminate\Database\Eloquent\Model;
use Spatie\Tags\HasTags;
class YourModel extends Model
{
use HasTags;
...
}
##Attaching tags
Here's how you can add some tags:
$yourModel->attachTag('tag 1');
$yourModel->attachTags(['tag 2', 'tag 3']);
The tags will be stored in the tags
-table. When using these functions we'll make sure that tags are unique and a model will have a tag attached only once.
##Detaching tags
Here's how tags can be detached:
$yourModel->detachTag('tag 1');
$yourModel->detachTags(['tag 2', 'tag 3']);
$yourModel->detach(\Spatie\Tags\Tag::find('tag4'));
##Syncing tags
By syncing tags the package will make sure only the tags given will be attached to the models. All other tags that were on the model will be detached.
$yourModel->syncTags(['tag 2', 'tag 3']);
##Managing tags
Tags are stored in the tags
table and can be managed with the included Spatie\Tags\Tag
-model.
$tag = Tag::create(['name' => 'my tag']);
$tag->name = 'another tag';
$tag->save();
$tag = Tag::findFromString('another tag');
$tag = Tag::findOrCreateFromString('yet another tag');
$tag->delete();
$tags = Tag::findFromStringOfAnyType('one more tag');
##Finding tags
You can find all tags containing a specific value with the containing
scope.
Tag::findOrCreate('one');
Tag::findOrCreate('another-one');
Tag::findOrCreate('another-ONE-with-different-casing');
Tag::findOrCreate('two');
Tag::containing('on')->get();
##Getting types
You can fetch a collection of all registered tag types by using the static method getTypes()
:
Tag::getTypes();
##Checking if a model has a tag
You can check if a model has a specific tag using the hasTag
method:
$yourModel->hasTag('tag 1');
$yourModel->hasTag('non-existing tag');
You can also check if a model has a tag with a specific type:
$yourModel->hasTag('tag 1', 'some_type');
$yourModel->hasTag('tag 1', 'non-existing type');