diff --git a/README.md b/README.md index 29b83a3..9ddf62e 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,28 @@ $translations = [ $newsItem->setTranslations('name', $translations); ``` +#### Replace translations in one go + +You can replace all the translations for a single key using this method: + +```php +public function replaceTranslations(string $key, array $translations) +``` + +Here's an example: + +```php +$translations = ['en' => 'hello', 'es' => 'hola']; + +$newsItem->setTranslations('hello', $translations); +$newsItem->getTranslations(); // ['en' => 'hello', 'es' => 'hola'] + +$newTranslations = ['en' => 'hello']; + +$newsItem->replaceTranslations('hello', $newTranslations); +$newsItem->getTranslations(); // ['en' => 'hello'] +``` + #### Setting the model locale The default locale used to translate models is the application locale, however it can sometimes be handy to use a custom locale. diff --git a/src/HasTranslations.php b/src/HasTranslations.php index 94eebff..edbd7b4 100644 --- a/src/HasTranslations.php +++ b/src/HasTranslations.php @@ -164,6 +164,17 @@ public function hasTranslation(string $key, string $locale = null): bool return isset($this->getTranslations($key)[$locale]); } + public function replaceTranslations(string $key, array $translations): self + { + foreach ($this->getTranslatedLocales($key) as $locale) { + $this->forgetTranslation($key, $locale); + } + + $this->setTranslations($key, $translations); + + return $this; + } + protected function guardAgainstNonTranslatableAttribute(string $key) { if (! $this->isTranslatableAttribute($key)) { diff --git a/tests/TranslatableTest.php b/tests/TranslatableTest.php index bba7d68..a5109e2 100644 --- a/tests/TranslatableTest.php +++ b/tests/TranslatableTest.php @@ -562,4 +562,18 @@ public function it_can_set_and_fetch_attributes_based_on_set_locale() $this->testModel->setLocale('fr'); $this->assertSame($fr, $this->testModel->name); } + + /** @test */ + public function it_can_replace_translations() + { + $translations = ['nl' => 'hallo', 'en' => 'hello', 'kh' => 'សួរស្តី']; + + $this->testModel->setTranslations('name', $translations); + $this->testModel->save(); + + $newTranslations = ['es' => 'hola']; + $this->testModel->replaceTranslations('name', $newTranslations); + + $this->assertEquals($newTranslations, $this->testModel->getTranslations('name')); + } }