Skip to content

Commit 9e7513c

Browse files
Merge pull request #517 from jimmitjoo/main
Add "hasTag" method to check if the model has a certain tag
2 parents 1e6d647 + 5a563b8 commit 9e7513c

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/HasTags.php

+9
Original file line numberDiff line numberDiff line change
@@ -300,4 +300,13 @@ protected function syncTagIds($ids, string | null $type = null, $detaching = tru
300300
$this->tags()->touchIfTouching();
301301
}
302302
}
303+
304+
public function hasTag($tag, string $type = null): bool
305+
{
306+
return $this->tags
307+
->when($type !== null, fn ($query) => $query->where('type', $type))
308+
->contains(function ($modelTag) use ($tag) {
309+
return $modelTag->name === $tag || $modelTag->id === $tag;
310+
});
311+
}
303312
}

tests/HasTagsTest.php

+22
Original file line numberDiff line numberDiff line change
@@ -362,3 +362,25 @@
362362
$tagsOfTypeA = $this->testModel->tagsWithType('typeA');
363363
expect($tagsOfTypeA->pluck('name')->toArray())->toEqual(['tagA1']);
364364
});
365+
366+
it('can check if it has a tag', function () {
367+
$tag = Tag::findOrCreate('test-tag');
368+
$anotherTag = Tag::findOrCreate('another-tag');
369+
370+
$this->testModel->attachTag($tag);
371+
372+
expect($this->testModel->hasTag('test-tag'))->toBeTrue();
373+
expect($this->testModel->hasTag($tag->id))->toBeTrue();
374+
expect($this->testModel->hasTag('non-existing-tag'))->toBeFalse();
375+
expect($this->testModel->hasTag($anotherTag->id))->toBeFalse();
376+
});
377+
378+
it('can check if it has a tag with type', function () {
379+
$tag = Tag::findOrCreate('test-tag', 'type1');
380+
$sameNameDifferentType = Tag::findOrCreate('test-tag', 'type2');
381+
382+
$this->testModel->attachTag($tag);
383+
384+
expect($this->testModel->hasTag('test-tag', 'type1'))->toBeTrue();
385+
expect($this->testModel->hasTag('test-tag', 'type2'))->toBeFalse();
386+
});

0 commit comments

Comments
 (0)