在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):dimsav/laravel-translatable开源软件地址(OpenSource Url):https://github.com/dimsav/laravel-translatable开源编程语言(OpenSource Language):PHP 100.0%开源软件介绍(OpenSource Introduction):This package has been deprecated. But worry not. You can use Astrotomic/laravel-translatable. Laravel-TranslatableIf you want to store translations of your models into the database, this package is for you. This is a Laravel package for translatable models. Its goal is to remove the complexity in retrieving and storing multilingual model instances. With this package you write less code, as the translations are being fetched/saved when you fetch/save your instance. Docs
DemoGetting translated attributes $greece = Country::where('code', 'gr')->first();
echo $greece->translate('en')->name; // Greece
App::setLocale('en');
echo $greece->name; // Greece
App::setLocale('de');
echo $greece->name; // Griechenland Saving translated attributes $greece = Country::where('code', 'gr')->first();
echo $greece->translate('en')->name; // Greece
$greece->translate('en')->name = 'abc';
$greece->save();
$greece = Country::where('code', 'gr')->first();
echo $greece->translate('en')->name; // abc Filling multiple translations $data = [
'code' => 'gr',
'en' => ['name' => 'Greece'],
'fr' => ['name' => 'Grèce'],
];
$greece = Country::create($data);
echo $greece->translate('fr')->name; // Grèce Laravel compatibility
Tutorials
Installation in 4 stepsStep 1: Install packageAdd the package in your composer.json by executing the command. composer require dimsav/laravel-translatable Next, add the service provider to
Step 2: MigrationsIn this example, we want to translate the model Schema::create('countries', function(Blueprint $table)
{
$table->increments('id');
$table->string('code');
$table->timestamps();
});
Schema::create('country_translations', function(Blueprint $table)
{
$table->increments('id');
$table->integer('country_id')->unsigned();
$table->string('name');
$table->string('locale')->index();
$table->unique(['country_id','locale']);
$table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
}); Step 3: Models
// models/Country.php
class Country extends Eloquent {
use \Dimsav\Translatable\Translatable;
public $translatedAttributes = ['name'];
protected $fillable = ['code'];
/**
* The relations to eager load on every query.
*
* @var array
*/
// (optionaly)
// protected $with = ['translations'];
}
// models/CountryTranslation.php
class CountryTranslation extends Eloquent {
public $timestamps = false;
protected $fillable = ['name'];
} The array Step 4: ConfigurationWe copy the configuration file to our project. Laravel 5.* php artisan vendor:publish --tag=translatable Laravel 4.* php artisan config:publish dimsav/laravel-translatable Note: There isn't any restriction for the format of the locales. Feel free to use whatever suits you better, like "eng" instead of "en", or "el" instead of "gr". The important is to define your locales and stick to them. ConfigurationThe config fileYou can see the options for further customization in the config file. The translation modelThe convention used to define the class of the translation model is to append the keyword So if your model is To use a custom class as translation model, define the translation class (including the namespace) as parameter. For example: <?php
namespace MyApp\Models;
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Country extends Eloquent
{
use Translatable;
public $translationModel = 'MyApp\Models\CountryAwesomeTranslation';
} Features listPlease read the installation steps first, to understand what classes need to be created. Available methods// Before we get started, this is how we determine the default locale.
// It is set by laravel or other packages.
App::getLocale(); // 'fr'
// To use this package, first we need an instance of our model
$germany = Country::where('code', 'de')->first();
// This returns an instance of CountryTranslation of using the default locale.
// So in this case, french. If no french translation is found, it returns null.
$translation = $germany->translate();
// It is possible to define a default locale per model by overriding the model constructor.
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->defaultLocale = 'de';
}
// It is also possible to define a default locale for our model on the fly:
$germany->setDefaultLocale('de');
// If an german translation exists, it returns an instance of
// CountryTranslation. Otherwise it returns null.
$translation = $germany->translate('de');
// If a german translation doesn't exist, it attempts to get a translation
// of the fallback language (see fallback locale section below).
$translation = $germany->translate('de', true);
// Alias of the above.
$translation = $germany->translateOrDefault('de');
// Returns instance of CountryTranslation of using the default locale.
// If no translation is found, it returns a fallback translation
// if enabled in the configuration.
$translation = $germany->getTranslation();
// If an german translation exists, it returns an instance of
// CountryTranslation. Otherwise it returns null.
// Same as $germany->translate('de');
$translation = $germany->getTranslation('de', true);
// To set the translation for a field you can either update the translation model.
// Saving the model will also save all the related translations.
$germany->translate('en')->name = 'Germany';
$germany->save();
// Alternatively we can use the shortcut
$germany->{'name:en'} = 'Germany';
$germany->save();
// There are two ways of inserting mutliple translations into the database
// First, using the locale as array key.
$greece = $country->fill([
'en' => ['name' => 'Greece'],
'fr' => ['name' => 'Grèce'],
]);
// The second way is to use the following syntax.
$greece = $country->fill([
'name:en' => 'Greece',
'name:fr' => 'Grèce',
]);
// Returns true/false if the model has translation about the current locale.
$germany->hasTranslation();
// Returns true/false if the model has translation in french.
$germany->hasTranslation('fr');
// If a german translation doesn't exist, it returns
// a new instance of CountryTranslation.
$translation = $germany->translateOrNew('de');
// Returns a new CountryTranslation instance for the selected
// language, and binds it to $germany
$translation = $germany->getNewTranslation('it');
// The eloquent model relationship. Do what you want with it ;)
$germany->translations();
// Remove all translations linked to an object
$germany->deleteTranslations();
// Delete one or multiple translations
$germany->deleteTranslations('de');
$germany->deleteTranslations(['de', 'en']);
// Gel all the translations as array
$germany->getTranslationsArray();
// Returns
[
'en' => ['name' => 'Germany'],
'de' => ['name' => 'Deutschland'],
'fr' => ['name' => 'Allemagne'],
];
// Creates a clone and clones the translations
$replicate = $germany->replicateWithTranslations(); Available scopes// Returns all countries having translations in english
Country::translatedIn('en')->get();
// Returns all countries not being translated in english
Country::notTranslatedIn('en')->get();
// Returns all countries having translations
Country::translated()->get();
// Eager loads translation relationship only for the default
// and fallback (if enabled) locale
Country::withTranslation()->get();
// Returns an array containing pairs of country ids and the translated
// name attribute. For example:
// [
// ['id' => 1, 'name' => 'Greece'],
// ['id' => 2, 'name' => 'Belgium']
// ]
Country::listsTranslations('name')->get()->toArray();
// Filters countries by checking the translation against the given value
Country::whereTranslation('name', 'Greece')->first();
// Filters countries by checking the translation against the given value, only in the specified locale
Country::whereTranslation('name', 'Greece', 'en')->first();
// Or where translation
Country::whereTranslation('name', 'Greece')->orWhereTranslation('name', 'France')->get();
// Filters countries by checking the translation against the given string with wildcards
Country::whereTranslationLike('name', '%Gree%')->first();
// Or where translation like
Country::whereTranslationLike('name', '%eece%')->orWhereTranslationLike('name', '%ance%')->get(); Magic propertiesTo use the magic properties, you have to define the property class Country extends Eloquent {
use \Dimsav\Translatable\Translatable;
public $translatedAttributes = ['name'];
} // Again we start by having a country instance
$germany = Country::where('code', 'de')->first();
// We can reference properties of the translation object directly from our main model.
// This uses the default locale and is the equivalent of $germany->translate()->name
$germany->name; // 'Germany'
// We can also quick access a translation with a custom locale
$germany->{'name:de'} // 'Deutschland' FallbackFallback localesIf you want to fallback to a default translation when a translation has not been found, enable this in the configuration
using the Configuration example: return [
'use_fallback' => true,
'fallback_locale' => 'en',
]; You can also define per-model the default for "if fallback should be used", by setting the class Country {
public $useTranslationFallback = true;
} Fallback per propertyEven though we try having all models nicely translated, some fields might left empty. What's the result? You end up with missing translations for those fields! The property fallback feature is here to help. When enabled, translatable will return the value of the fallback language for those empty properties. The feature is enabled by default on new installations. If your config file was setup before v7.1, make sure to add the following line to enable the feature: 'use_property_fallback' => true, Of course the fallback locales must be enabled to use this feature. If the property fallback is enabled in the configuration, then translatable will return the translation of the fallback locale for the fields where the translation is empty. customize empty translation property detectionThis package is made to translate strings, but in general it's also able to translate numbers, bools or whatever you want to. By default a simple protected function isEmptyTranslatableAttribute(string $key, $value): bool
{
switch($key) {
case 'name':
return empty($value);
case 'price':
return !is_number($value);
default:
return is_null($value);
}
} Country based fallbackSince version v5.3 it is possible to use country based locales. For example, you can have the following locales:
To configuration for these locales looks like this: 'locales' => [
'en',
'es' => [
'MX',
'CO',
],
]; We can also configure the "glue" between the language and country. If for instance we prefer the format 'locale_separator' => '_', What applies for the fallback of the locales using the Let's say our fallback locale is Translation AutoloadingIf the
Add onsThanks to the community a few packages have been written to make usage of Translatable easier when working with forms: FAQI need some example code!Examples for all the package features can be found in the code used for the tests. I need help!Got any question or suggestion? Feel free to open an Issue. I want to help!You are awesome! Watch the repo and reply to the issues. You will help offering a great experience to the users of the package. Also buy me a beer by m |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论