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
);

> // 1. Top-Level Strings
> $post->getTranslation('title', 'en'); // 'Hello World'
> $post->title;                         // 'Hello World'
>
> // 2. Top-Level JSON Casts (Translatable category tags)
> $post->getTranslation('tags', 'en');  // '["news","tutorials","releases"]' (Raw string)
> $post->tags;                          // ['news', 'tutorials', 'releases']  (Casted array)
>
> // 3. Nested Strings
> $post->getTranslation('meta.seo.description', 'en'); // '"Learn Laravel package design"' (Raw JSON string)
> $post->meta['seo']['description'];                   // 'Learn Laravel package design'   (Decoded string)
>
> // 4. Nested JSON Arrays
> $post->getTranslation('content_blocks.featured_quotes', 'en'); // '["Clean code matters","Test everything"]'
> $post->content_blocks['featured_quotes'];                      // ['Clean code matters', 'Test everything']
> 

$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();

> // 1. Top-Level Strings
> $post->setTranslation('title', 'Hello World', 'en');
> $post->title = 'Hello World';
> 
> // 2. Top-Level JSON Casts (Translatable category tags)
> $post->setTranslation('tags', json_encode(['news', 'tutorials', 'releases']), 'en');
> $post->tags = ['news', 'tutorials', 'releases'];
> 
> // 3. Nested Strings
> $post->setTranslation('meta.seo.description', json_encode('Learn Laravel package design'), 'en');
> $post->meta = ['seo' => ['description' => 'Learn Laravel package design'], 'robots' => 'index'];
> 
> // 4. Nested JSON Arrays
> $post->setTranslation('content_blocks.featured_quotes', json_encode(['Clean code matters', 'Test everything']), 'en');
> $post->content_blocks = ['featured_quotes' => ['Clean code matters', 'Test everything']];
> 

$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();

protected function translatables(): array
{
    return ['variants.*.label']; // Matches variants.0.label, variants.1.label, ...
}

$product->variants = [
    ['id' => 1, 'sku' => 'RED-M', 'label' => null],
    ['id' => 2, 'sku' => 'BLU-M', 'label' => null],
];
$product->save();

$product->{'variants->0->label'} = 'Red / Medium';
$product->{'variants->1->label'} = 'Blue / Medium';
$product->save();

protected function translatables(): array
{
    return ['items.*:uuid.answer'];
}

class Setting extends Model
{
    use HasTranslations;

    protected $fillable = ['key', 'value'];

    protected $casts = ['value' => 'array'];

    public function hasDynamicTranslatables(): bool
    {
        return true;
    }
}

$generalSettings = Setting::create([
    'key' => 'general_settings',
    'value' => []
]);

$generalSettings->rememberDynamicTranslatable('value.app_name');
$generalSettings->setTranslation('value.app_name', 'Laravel Translatable Model', 'en');
$generalSettings->save();

$settings = $generalSettings->value; // => ['app_name' => 'Laravel Translatable Model'] — translated, current locale

$post->getTranslation('title', 'ar', NoFallbackStrategy::class);

> $value = $model->column;
> $value['key'] = 'new value';
> $model->column = $value;
> 

Post::where('title', 'like', '%hello%')
    ->orderBy('title')
    ->get();

Post::whereIn('meta->title', ['Hello', 'Hi'])->get();

Post::pluck('title', 'id');

Post::where('meta->title', 'like', '%hello%')->get();

$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
bash
    php artisan vendor:publish --tag="translatable-model-config"
    
bash
    php artisan vendor:publish --tag="translatable-model-migrations"
    
bash
    php artisan migrate