Retrieving the translated data

You can access the translated attribute easily.

App::setLocale('en');

$product = Product::first();

echo $product->description; // Product description in English

$product->translateTo('es');
echo $product->description; // Product description in Spanish
echo $product->details;     // Product details in Spanish

Retrieve all the translatable attribute values

$product = Product::first();

dd($product->getAllTranslationValues());

The example above will return result like this

array:2 [
  "description" => array:2 [
    "en" => "Product description in English"
    "es" => "Product description in Spanish"
  ]
  "details"     => array:2 [
    "en" => "Product details in English"
    "es" => "Product details in Spanish"
  ]
]

Model serialization

App::setLocale('es');

dd(
    Product::first()
        ->setAppends(['description', 'details'])
        ->toArray()
);

The example above will return result like this

array:7 [
  "id"          => 1
  "name"        => "Amazon Kindle Oasis"
  "published"   => true
  "created_at"  => "2022-02-22T00:00:00.000000Z"
  "updated_at"  => "2022-02-22T00:00:00.000000Z"
  "description" => "Product description in Spanish"
  "details"     => "Product details in Spanish"
]

Translate an eloquent collection

You can also translate an eloquent collection which contains TranslatableModel instances.

$products = Product::all();

// Translate all models in the collection
$products->translateTo('es');
Edit this page on GitHub Updated at Wed, May 25, 2022