Skip to content

Commit

Permalink
Merge pull request #517 from jimmitjoo/main
Browse files Browse the repository at this point in the history
Add "hasTag" method to check if the model has a certain tag
  • Loading branch information
AlexVanderbist authored Oct 3, 2024
2 parents 1e6d647 + 5a563b8 commit 9e7513c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/HasTags.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
}
}
22 changes: 22 additions & 0 deletions tests/HasTagsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

0 comments on commit 9e7513c

Please sign in to comment.