Laravel Translations
, (*1)
Easily translate your laravel models to as many languages you need., (*2)
Installation
Add this line to your composer.json file:, (*3)
"escapework/laravel-translations": "0.2.*"
And add this service provider to your laravel providers:, (*4)
EscapeWork\Translations\TranslationServiceProvider::class
And publish the migrations running the following command:, (*5)
$ php artisan vendor:publish --provider="EscapeWork\Translations\TranslationServiceProvider"
$ php artisan migrate
Usage
Creating the locales
First, you need to create the locales that your models will be translated., (*6)
EscapeWork\Translations\Locale::create(['id' => 'pt-br', 'title' => 'PortuguĂȘs (Brasil)']);
EscapeWork\Translations\Locale::create(['id' => 'en', 'title' => 'English']);
Then, you need to import the Translatable in your models., (*7)
use EscapeWork\Translations\Translatable;
...
class Product extends Model
{
use Translatable;
}
Storing a translation
For storing a translation, you can do the following:, (*8)
// $data can have as many fields you want
$data = [
'title' => 'My translated title',
'description' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit',
];
$product->storeTranslation((array) $data, 'pt-br');
Here it's an example on how you can use with Laravel $request object., (*9)
$product = Product::find(1);
foreach ((array) $request->translations as $locale => $data) {
$product->storeTranslation((array) $data, $locale);
}
Deleting translations from a model
$product->deleteTranslations();
Getting a translation
For getting an existing translation, you just need to do this:, (*10)
$product = Product::find(1);
echo $product->translations->_get('title'); // this will get the translation for the current config('app.locale') value
If you need an translation for an specific locale, just pass the locale as the second argument:, (*11)
$product = Product::find(1);
echo $product->translations->_get('title', 'pt-br');
If you don't pass the $locale, the default is gonna be the config('app.locale') value., (*12)
You can also do something like this to make your life easier:, (*13)
class Product extends Model
{
...
public function getTitleAttribute()
{
return $this->translations->_get('title');
}
...
}
// then, just call like a simple field
echo $product->title;
Next steps
- Testing;
- Make use of MySQL 5.7 JSON types, where a search inside the translations will be available;
License
See the License file., (*14)