Skip to content

Commit

Permalink
Merge pull request #2 from mihkelallorg/get-translated
Browse files Browse the repository at this point in the history
Add getTranslated method
  • Loading branch information
mihkelallorg authored Mar 6, 2019
2 parents f4bfbc6 + 6c896e1 commit 17ca4d4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Traits/Translatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Mihkullorg\Translatable\Traits;

use Illuminate\Support\Facades\App;
use Mihkullorg\Translatable\Facades\Translator;
use Mihkullorg\Translatable\Models\Translation;
use Illuminate\Database\Eloquent\Relations\MorphMany;
Expand Down Expand Up @@ -93,4 +94,19 @@ public function getTranslationsAsArray()
$values->put('language', $language);
})->values()->toArray();
}

/**
* Get the translated field value.
*
* @param $field
* @param null $language Defaults to the App locale
* @param null $default The return value if the translation does not exist
* @return string
*/
public function getTranslated($field, $language = null, $default = null)
{
$language = $language ?: App::getLocale();

return object_get($this->translation($field, $language), 'value', $default);
}
}
19 changes: 19 additions & 0 deletions tests/TranslatableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Mihkullorg\Tests\Translatable;

use Carbon\Carbon;
use Illuminate\Support\Facades\App;
use Mihkullorg\Translatable\Facades\Translator;
use Mihkullorg\Tests\Translatable\Models\TestModel;

Expand Down Expand Up @@ -85,6 +86,24 @@ public function test_retrieve_translations_as_array()
], $translations));
}

public function test_get_translated_method()
{
/** @var TestModel $model */
$model = factory(TestModel::class)->create();

$field = 'body';
$englishTranslation = 'English translation';
$model->createTranslation($field, 'en', $englishTranslation);

$this->assertEquals($model->getTranslated('body', 'en'), $englishTranslation);

App::setLocale('ru');
$this->assertNull($model->getTranslated('body'));

App::setLocale('en');
$this->assertEquals($model->getTranslated('body'), $englishTranslation);
}

/**
* @param TestModel $model
* @param $field
Expand Down

0 comments on commit 17ca4d4

Please sign in to comment.