PHP code example of alnaggar / laravel-translatable-model
1. Go to this page and download the library: Download alnaggar/laravel-translatable-model 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/ */
alnaggar / laravel-translatable-model example snippets
use Alnaggar\TranslatableModel\HasTranslations;
class Post extends Model
{
use HasTranslations;
protected function casts(): array
{
return [
'meta' => 'array',
];
}
protected function translatables(): array
{
return [
'title',
'body',
'meta.title',
'meta.description',
];
}
}
$titleAr = $post->getTranslation(
key: 'title',
locale: 'ar', // null for current locale
fallbackStrategy: DedicatedLocaleFallbackStrategy::class.':en' // see Fallback Strategies
);
// Laravel-style retrievement in current locale, applying the model's
// (or config's) default fallback strategy
$titleAr = $post->title;
$titleAr = $post['title'];
$allTitles = $post->getTranslations(
key: 'title',
locales: null // Applying every locale the model has translations for
fallbackStrategy: null // Applying the model's (or config's) default fallback strategy
);
$post->setTranslation(
key: 'title',
translation: 'Hello world',
locale: 'en' // null for current locale
);
// Laravel-style assignment in current locale
$post->title = 'Bonjour à tous';
$post['title'] = 'Bonjour à tous';
$post->setTranslations(
key: 'title',
translations: ['ar' => 'مرحبا', 'en' => 'Hello', 'fr' => 'Bonjour à tous']
);
// Translations are upserted when the model is saved
$post->save();
$post->removeTranslation(
key: 'meta.description',
locale: 'fr' // null for current locale
);
$post->removeTranslationsForKeys(['title', 'meta.description']); // Every translation for these keys across all locales
$post->removeTranslationsForLocales('fr'); // Every translation for this locale (accepts an array too)
$post->flushAllTranslations(); // Everything
$post->save();
if ($post->hasTranslation('title', 'ar')) {
// Arabic translation exists
}
protected function translatables(): array
{
return ['meta.description'];
}
$post->meta; // => ['author' => 'Ahmad', 'description' => 'Translated value']
$post->meta = ['author' => 'Ahmad', 'description' => 'A translations management project'];
// Or, targeting just the leaf directly:
$post['meta->description'] = 'A translations management project';
$post->save();
$post = TranslatableModel::withoutTranslations(function () {
return Post::create([
'title' => 'untitled', // Stored as-is, in the title column itself — not a translation
'meta' => ['author' => 'Ahmad', 'description' => 'no description yet'], // Same thing applies to meta.description
]);
});
$post = Post::find(1)->disableTranslations();
$post->title = 'untitled'; // Stored as-is, in the title column — not a translation, regardless of the facade's global toggle