diff --git a/src/HasTags.php b/src/HasTags.php index 98950c3..801cb24 100644 --- a/src/HasTags.php +++ b/src/HasTags.php @@ -300,4 +300,13 @@ protected function syncTagIds($ids, string | null $type = null, $detaching = tru $this->tags()->touchIfTouching(); } } + + public function hasTag($tag, string $type = null): bool + { + return $this->tags + ->when($type !== null, fn ($query) => $query->where('type', $type)) + ->contains(function ($modelTag) use ($tag) { + return $modelTag->name === $tag || $modelTag->id === $tag; + }); + } } diff --git a/tests/HasTagsTest.php b/tests/HasTagsTest.php index 9971409..74dd25f 100644 --- a/tests/HasTagsTest.php +++ b/tests/HasTagsTest.php @@ -362,3 +362,25 @@ $tagsOfTypeA = $this->testModel->tagsWithType('typeA'); expect($tagsOfTypeA->pluck('name')->toArray())->toEqual(['tagA1']); }); + +it('can check if it has a tag', function () { + $tag = Tag::findOrCreate('test-tag'); + $anotherTag = Tag::findOrCreate('another-tag'); + + $this->testModel->attachTag($tag); + + expect($this->testModel->hasTag('test-tag'))->toBeTrue(); + expect($this->testModel->hasTag($tag->id))->toBeTrue(); + expect($this->testModel->hasTag('non-existing-tag'))->toBeFalse(); + expect($this->testModel->hasTag($anotherTag->id))->toBeFalse(); +}); + +it('can check if it has a tag with type', function () { + $tag = Tag::findOrCreate('test-tag', 'type1'); + $sameNameDifferentType = Tag::findOrCreate('test-tag', 'type2'); + + $this->testModel->attachTag($tag); + + expect($this->testModel->hasTag('test-tag', 'type1'))->toBeTrue(); + expect($this->testModel->hasTag('test-tag', 'type2'))->toBeFalse(); +});