Skip to content

Commit e5dcbdc

Browse files
Add: hasTranslation method
1 parent 3c8b200 commit e5dcbdc

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,19 @@ $post->title_nl
5656
$post->getTranslation('title', 'nl')
5757
```
5858

59+
To check if a translation exists, you may use the `hasTranslation` method:
60+
```php
61+
$post->title_en = 'Your first translation';
62+
$post->title_nl = '';
63+
$post->title_fr = null;
64+
65+
$post->hasTranslation('title', 'en'); // returns true
66+
$post->hasTranslation('title', 'nl'); // returns false
67+
$post->hasTranslation('title', 'fr'); // returns false
68+
```
69+
70+
In case you do not supply a locale, the current locale will be used.
71+
5972
### Using a fallback
6073
This package allows you to return the value of an attribute's `fallback_locale` defined in the `config/app.php` of your application.
6174

src/UnderscoreTranslatable.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ public function getTranslationWithoutFallback(string $key, ?string $locale = nul
4242
return $this->getTranslation($key, $locale, false);
4343
}
4444

45+
public function hasTranslation(string $key, ?string $locale = null): bool
46+
{
47+
return ! empty($this->getTranslationWithoutFallback($key, $locale));
48+
}
49+
4550
public function setTranslation(string $key, string $locale, mixed $value): self
4651
{
4752
if ($this->hasSetMutator($key)) {

tests/UnderscoreTranslatableTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,19 @@ public function it_can_get_a_translation_using_an_accessor()
142142
$this->assertEquals('test en', $post->field_with_accessor);
143143
}
144144

145+
/** @test */
146+
public function it_can_check_if_it_has_a_translation()
147+
{
148+
$post = new Post();
149+
$post->title_en = 'Test en';
150+
$post->title_nl = '';
151+
$post->title_fr = null;
152+
153+
$this->assertTrue($post->hasTranslation('title', 'en'));
154+
$this->assertFalse($post->hasTranslation('title', 'nl'));
155+
$this->assertFalse($post->hasTranslation('title', 'fr'));
156+
}
157+
145158
/** @test */
146159
public function it_can_set_a_translatable_attribute_using_a_method()
147160
{

0 commit comments

Comments
 (0)