Skip to content
This repository has been archived by the owner on Jun 18, 2019. It is now read-only.

A model can have a default locale for translations #271

Merged
merged 3 commits into from
Jan 29, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/Translatable/Translatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

trait Translatable
{
protected $defaultLocale;

/**
* Alias for getTranslation().
*
Expand Down Expand Up @@ -620,10 +622,38 @@ private function getTranslationsTable()
*/
protected function locale()
{
if ($this->defaultLocale) {
return $this->defaultLocale;
}

return app()->make('config')->get('translatable.locale')
?: app()->make('translator')->getLocale();
}

/**
* Set the default locale on the model.
*
* @param $locale
*
* @return $this
*/
public function setDefaultLocale($locale)
{
$this->defaultLocale = $locale;

return $this;
}

/**
* Get the default locale on the model.
*
* @return mixed
*/
public function getDefaultLocale()
{
return $this->defaultLocale;
}

/**
* Deletes all translations for this model.
*
Expand Down
20 changes: 20 additions & 0 deletions tests/TranslatableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -509,4 +509,24 @@ public function test_fill_with_translation_key()
$this->assertEquals($country->translate('en')->name, 'Turkey');
$this->assertEquals($country->translate('de')->name, 'Türkei');
}

public function test_it_uses_the_default_locale_from_the_model()
{
$country = new Country();
$country->fill([
'code' => 'tn',
'name:en' => 'Tunisia',
'name:fr' => 'Tunisie',
]);
$this->assertEquals($country->name, 'Tunisia');
$country->setDefaultLocale('fr');
$this->assertEquals($country->name, 'Tunisie');

$country->setDefaultLocale(null);
$country->save();
$country = Country::whereCode('tn')->first();
$this->assertEquals($country->name, 'Tunisia');
$country->setDefaultLocale('fr');
$this->assertEquals($country->name, 'Tunisie');
}
}