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/ */
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')
->
// 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(),
];
}