PHP code example of nramos / translatable

1. Go to this page and download the library: Download nramos/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/ */

    

nramos / translatable example snippets


return [
    'locales' => ['en', 'fr', 'es', 'de', 'it'],
    'fallback_locale' => 'en',
    'translations_table' => 'model_translations',
    'auto_load_translations' => true,
];



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Nramos\Translatable\Traits\HasTranslations;

class Product extends Model
{
    use HasTranslations;

    protected $translatableAttributes = [
        '__name',
        '__description',
    ];

    protected $fillable = [
        'price',
        'sku',
        'name',        // Colonne fallback (optionnelle)
        'description', // Colonne fallback (optionnelle)
    ];
}

// Créer un produit avec traductions
$product = new Product();
$product->sku = 'PROD-001';
$product->price = 99.99;

// Français
app()->setLocale('fr');
$product->name = 'Produit fantastique';
$product->description = 'Une description en français';

// Anglais  
app()->setLocale('en');
$product->name = 'Amazing Product';
$product->description = 'An english description';

$product->save();

// Récupérer selon la locale courante
app()->setLocale('fr');
echo $product->name; // "Produit fantastique"

app()->setLocale('en');
echo $product->name; // "Amazing Product"

// Définir une traduction spécifique
$product->setTranslation('__name', 'es', 'Producto increíble');

// Récupérer une traduction spécifique
$spanishName = $product->getTranslation('__name', 'es');

// Récupérer toutes les traductions d'un attribut
$allNames = $product->getTranslations('__name');
// ['fr' => 'Produit fantastique', 'en' => 'Amazing Product', 'es' => 'Producto increíble']

$frenchName = Product::withLocale('fr', function() use ($product) {
    return $product->name;
});

// Charger les traductions pour éviter les requêtes N+1
$products = Product::withTranslations(['fr', 'en'])->get();

// Ou pour la locale courante seulement
$products = Product::withTranslations()->get();

// Dans votre Resource
public static function form(Form $form): Form
{
    return $form->schema([
        Forms\Components\TextInput::make('name')
            ->label('Nom du produit')
            ->

Schema::create('model_translations', function (Blueprint $table) {
    $table->id();
    $table->morphs('translatable'); // translatable_type + translatable_id
    $table->string('locale', 10);
    $table->string('attribute_name');
    $table->longText('value');
    $table->timestamps();

    $table->unique(['translatable_type', 'translatable_id', 'locale', 'attribute_name']);
});

class Product extends Model
{
    use HasTranslations;

    protected $translatableAttributes = [
        '__name',
        '__description',
        '__short_description',
        '__seo_title',
        '__meta_description',
    ];
}

// Migration de migration des données existantes
$products = Product::all();

foreach ($products as $product) {
    if ($product->getOriginal('name')) {
        $product->setTranslation('__name', 'fr', $product->getOriginal('name'));
        $product->save();
    }
}

class Product extends Model
{
    use HasTranslations;

    protected $translatableAttributes = ['__name', '__description', '__short_description'];

    public function getLocalizedSlugAttribute()
    {
        return Str::slug($this->name);
    }
}

// Usage
app()->setLocale('fr');
$product->name = 'Chaussures de sport';
echo $product->localized_slug; // "chaussures-de-sport"

app()->setLocale('en');
$product->name = 'Sports shoes';
echo $product->localized_slug; // "sports-shoes"

class Article extends Model
{
    use HasTranslations;

    protected $translatableAttributes = [
        '__title',
        '__content', 
        '__excerpt',
        '__seo_title',
        '__meta_description'
    ];
}

class MenuItem extends Model
{
    use HasTranslations;

    protected $translatableAttributes = [
        '__name',
        '__description',
        '__ingredients'
    ];

    protected $casts = [
        'price' => 'decimal:2',
    ];
}

// ❌ Cause des requêtes N+1
$products = Product::all();
foreach ($products as $product) {
    echo $product->name;
}

// ✅ Une seule requête supplémentaire
$products = Product::withTranslations()->get();
foreach ($products as $product) {
    echo $product->name;
}

// Charger seulement les locales nécessaires
$products = Product::withTranslations(['fr', 'en'])->get();

// Dans config/translatable.php
'cache_translations' => true,
'cache_duration' => 3600, // 1 heure

// Ancien code spatie
$product->setTranslation('name', 'fr', 'Mon produit');

// Nouveau code avec ce package  
$product->setTranslation('__name', 'fr', 'Mon produit');
// ou plus simple :
app()->setLocale('fr');
$product->name = 'Mon produit';

// Dans un modèle pour debug
public function debugTranslations()
{
    return [
        'translatable_attributes' => $this->getTranslatableAttributes(),
        'pending_translations' => $this->debugPendingTranslations(),
        'current_locale' => $this->getCurrentLocale(),
        'existing_translations' => $this->translations->toArray(),
    ];
}
bash
php artisan vendor:publish --tag="translatable-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="translatable-config"
bash
# Trouver les traductions manquantes
php artisan translatable:missing

# Nettoyer les traductions orphelines
php artisan translatable:cleanup

# Exporter les traductions
php artisan translatable:export --locale=fr