PHP code example of weboccult / laravel-translatable
1. Go to this page and download the library: Download weboccult/laravel-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/ */
weboccult / laravel-translatable example snippets
use WebOccult\LaravelTranslatable\Traits\HasTranslations;
class Department extends Model
{
use HasTranslations;
protected $fillable = [
'code' // non-translatable field
];
// Define which attributes can be translated
protected $translatable = [
'name',
'description',
'address'
];
}
// Create a new department
$department = Department::create([
'code' => 'IT-001'
]);
// Method 1: Set translations one by one
$department->setTranslation('name', 'Information Technology', 'en');
$department->setTranslation('name', 'Technologies de l\'information', 'fr');
$department->setTranslation('name', 'Tecnología de la Información', 'es');
// Method 2: Set multiple translations at once
$department->updateTranslations([
'name' => [
'en' => 'Information Technology',
'fr' => 'Technologies de l\'information',
'es' => 'Tecnología de la Información'
],
'description' => [
'en' => 'Main IT Department',
'fr' => 'Département principal des TI',
'es' => 'Departamento Principal de TI'
]
]);
// Method 3: Set multiple fields for same locale
$department->setTranslation(
['name', 'description'],
['IT Department', 'Handles all IT operations'],
'en'
);
// Method 1: Get single translation
$name = $department->getTranslation('name', 'en');
// Output: "Information Technology"
// Method 2: Get all translations for an attribute
$allNames = $department->getAllTranslations('name');
// Output:
// [
// 'en' => 'Information Technology',
// 'fr' => 'Technologies de l\'information',
// 'es' => 'Tecnología de la Información'
// ]
// Method 3: Load with translations for current locale
$departments = Department::withTranslations()->get();
foreach ($departments as $dept) {
echo $dept->getTranslation('name'); // Uses current locale
}
// Method 4: Load with all translations
$department = Department::with('translations')->find(1);
$translations = $department->translations->groupBy('locale');
// Output:
// [
// 'en' => [
// ['attribute' => 'name', 'value' => 'Information Technology'],
// ['attribute' => 'description', 'value' => 'Main IT Department']
// ],
// 'fr' => [
// ['attribute' => 'name', 'value' => 'Technologies de l\'information'],
// ['attribute' => 'description', 'value' => 'Département principal des TI']
// ]
// ]