diff --git a/src/HasTags.php b/src/HasTags.php index 4f5b24c..624b27f 100644 --- a/src/HasTags.php +++ b/src/HasTags.php @@ -302,4 +302,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 a01553c..eb010e9 100644 --- a/tests/HasTagsTest.php +++ b/tests/HasTagsTest.php @@ -349,3 +349,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(); +});