Once your model is properly configured, translated attributes work like any other attribute. Basic operations will always run in the current locale unless you specify another one.
Get an attribute in the curent locale or fallback to the default locale:
echo $product->name;
You can force a specific locale with ->in($locale)
. If the translation doesn't exist, it will not fallback. in()
also changes the default locale on the model.
// Output the name in french or null, no fallback.
echo $product->in('fr')->name;
echo $product->description; // Still in french
To get raw values, use ->raw('attribute')
. You can also set the default locale to *
to disable localization:
echo $product->raw('name'); // ['en' => 'name']
dd($product->description); // "The description"
echo $product->in('*')->name; // ['en' => 'name']
dd($product->description); // ['en' => 'The description']
$product->toArray();
// Output
[
'id' => 1,
'name' => 'Product name',
// ...
]
$product->in('fr')->toArray();
// Output
[
'id' => 1,
'name' => 'Nom du produit',
// ...
]
$product->in('*')->toArray();
// Output
[
'id' => 1,
'name' => ['en' => 'Product name', 'fr' => 'Nom du produit'],
// ...
]
By default, entries are created in the current locale:
Product::create([
'name' => 'Product name',
]);
You can set multiple translations at once:
Product::create([
'name' => [
'en' => 'Product name',
'fr' => 'Nom du produit',
],
'description' => 'Description ...', // description will be set in the current locale only
]);
// Using arrow notation
Product::create([
'name->en' => 'Product name',
'name->fr' => 'Nom du produit',
'description' => 'Description ...',
]);
Updating an entry in the current locale
$product->update([
'name' => 'test'
]);
You can specify a locale for the update
// Update translation for a specific locale
$product->in('fr')->update([
'name' => 'test'
]);
Or set multiple locales at once
// Using arrow notation
$product->update([
'name->en' => 'Product name',
'name->fr' => 'Nom du produit',
]);
When passing an array, the value gets overridden
// Override all translations using an array
$product->update([
'name' => [
'en' => 'Product name',
'fr' => 'Nom du produit',
],
]);