PHP code example of uyoobonga / words-translatable
1. Go to this page and download the library: Download uyoobonga/words-translatable library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// 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'];
}
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';
}
// 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();
// 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();
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'
class Country {
public $useTranslationFallback = true;
}
'use_property_fallback' => true,
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);
}
}
'locales' => [
'en',
'es' => [
'MX',
'CO',
],
];
'locale_separator' => '_',
// We insert the translation attributes into the fresh translated table:
\DB::statement("insert into country_translations (country_id, name, locale) select id, name, 'en' from countries");
// We drop the translation attributes in our main table:
Schema::table('countries', function ($table) {
$table->dropColumn('name');
});
Country::join('country_translations as t', function ($join) {
$join->on('countries.id', '=', 't.country_id')
->where('t.locale', '=', 'en');
})
->groupBy('countries.id')
->orderBy('t.name', 'desc')
->with('translations')
->get();
Country::whereHas('translations', function ($query) {
$query->where('locale', 'en')
->where('name', 'Portugal');
})->first();
public function up()
{
DB::statement('ALTER TABLE countries ENGINE=InnoDB');
}
public function down()
{
DB::statement('ALTER TABLE countries ENGINE=MyISAM');
}