PHP code example of mindtwo / laravel-translatable

1. Go to this page and download the library: Download mindtwo/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/ */

    

mindtwo / laravel-translatable example snippets




use mindtwo\LaravelTranslatable\Models\Translatable;
use mindtwo\LaravelTranslatable\Resolvers\LocaleResolver;

return [
    /*
    |--------------------------------------------------------------------------
    | Translatable Model
    |--------------------------------------------------------------------------
    |
    | The model class to use for storing translations.
    |
    */
    'model' => Translatable::class,

    /*
    |--------------------------------------------------------------------------
    | Locale Resolver
    |--------------------------------------------------------------------------
    |
    | The resolver class to use for determining locale fallback chains.
    |
    */
    'resolver' => LocaleResolver::class,

    /*
    |--------------------------------------------------------------------------
    | Auto Translate Attributes
    |--------------------------------------------------------------------------
    |
    | When enabled, translatable attributes will be automatically translated
    | when accessed via magic attribute accessors (e.g., $model->title).
    | This can be overridden per model by implementing the autoTranslateAttributes() method.
    |
    */
    'auto_translate_attributes' => true,

    /*
    |--------------------------------------------------------------------------
    | Default Locale on Model
    |--------------------------------------------------------------------------
    |
    | When enabled, the default locale returned by the locale resolver is considered
    | to be stored on the model itself, i.e. not available in the translatable table
    | but stored directly in fields in the model table.
    |
    */
    'default_locale_on_model' => false,
];



use Illuminate\Database\Eloquent\Model;
use mindtwo\LaravelTranslatable\Traits\HasTranslations;

class Product extends Model
{
    use HasTranslations;

    protected $fillable = ['title', 'description', 'price'];

    /**
     * Define which fields are translatable
     */
    protected $translatable = ['title', 'description'];
}

$product = Product::create([
    'title' => 'Default Title',
    'description' => 'Default Description',
    'price' => 99.99
]);

// Add individual translations
$product->setTranslation('title', 'English Product', 'en');
$product->setTranslation('title', 'Deutsches Produkt', 'de');
$product->setTranslation('title', 'Produit Français', 'fr');

// Or add multiple translations at once for a locale
$product->setTranslations([
    'title' => 'English Product',
    'description' => 'English Description',
], 'en');

// Set application locale
app()->setLocale('de');

// Load model with translations
$product = Product::withTranslations()->first();
echo $product->title; // "Deutsches Produkt" (automatically translated!)
echo $product->description; // "Deutsche Beschreibung"
echo $product->price; // 99.99 (non-translated field remains unchanged)

// Get original value if needed
echo $product->getUntranslated('title'); // "Default Title"

// Get specific translation
echo $product->getTranslation('title', 'en'); // "English Product"

// Get all translations for a key
$titles = $product->getAllTranslations('title');
// ['en' => 'English Product', 'de' => 'Deutsches Produkt', 'fr' => 'Produit Français']

// Eager load translations for current locale
$products = Product::withTranslations()->get();

// Eager load translations for specific locales
$products = Product::withTranslations(['en', 'de'])->get();

// Search in translated fields (with fallback locale support)
$products = Product::searchByTranslation('title', 'Product')->get();

// Search in specific locales
$products = Product::searchByTranslation('title', 'Product', ['en', 'de'])->get();

// Exact match search
$exact = Product::searchByTranslationExact('title', 'Deutsches Produkt')->get();

// Prefix/suffix search
$startsWith = Product::searchByTranslationStartsWith('title', 'German')->get();
$endsWith = Product::searchByTranslationEndsWith('description', 'warranty')->get();

// Multiple field search
$multiField = Product::searchByTranslation(['title', 'description'], 'search term')->get();

// Filter models that have a translation
$hasTitle = Product::whereHasTranslation('title')->get();
$hasGermanTitle = Product::whereHasTranslation('title', 'de')->get();

// Filter by exact translation value
$products = Product::whereTranslation('title', 'Exact Title')->get();

// Order by translated field
$sorted = Product::orderByTranslation('title', 'asc')->get();

// Method chaining works perfectly
$results = Product::searchByTranslationStartsWith('title', 'Premium')
    ->whereHasTranslation('description')
    ->orderByTranslation('title')
    ->limit(10)
    ->get();

// The LocaleResolver provides locales in this order:
// 1. Current application locale: app()->getLocale()
// 2. Fallback locale: app()->getFallbackLocale()

use mindtwo\LaravelTranslatable\Resolvers\LocaleResolver;

class CustomLocaleResolver extends LocaleResolver
{
    public function getLocales(): array
    {
        // Return custom locale chain
        return ['de', 'en', 'fr'];
    }
}

'resolver' => \App\Services\CustomLocaleResolver::class,

use mindtwo\LaravelTranslatable\Resolvers\LocaleResolver;

$resolver = app(LocaleResolver::class);
$resolver->setLocales(['de', 'en', 'fr']);

// Now queries will use this locale chain
$products = Product::withTranslations()->get();

// Check if translation exists
if ($product->hasTranslation('title', 'de')) {
    echo "German translation available";
}

// Get specific translation (returns translated text)
$translation = $product->getTranslation('title', 'en');
echo $translation; // "English Product"

// Get translations for specific locales
$translations = $product->getTranslations('title', ['en', 'de']);
// ['en' => 'English Product', 'de' => 'Deutsches Produkt']

// Get all translations for a key
$allTitles = $product->getAllTranslations('title');
// ['en' => 'English Product', 'de' => 'Deutsches Produkt', 'fr' => 'Produit Français']

// Access the translations relationship
$translationModels = $product->translations;
foreach ($translationModels as $translation) {
    echo "{$translation->locale}: {$translation->key} = {$translation->text}";
}

// Product.php
class Product extends Model
{
    use HasTranslations;

    protected $translatable = ['title', 'description', 'features'];
}

// Category.php
class Category extends Model
{
    use HasTranslations;

    protected $translatable = ['name', 'description'];
}

// Article.php
class Article extends Model
{
    use HasTranslations;

    protected $translatable = ['title', 'content', 'excerpt', 'meta_description'];

    // Disable auto-translation for this model if needed
    protected function autoTranslateAttributes(): bool
    {
        return false;
    }
}

// Property approach (recommended)
protected $translatable = ['title', 'description'];

// Or method approach (for backwards compatibility)
public function translatedKeys(): array
{
    return ['title', 'description'];
}

// Disable auto-translation for specific model
protected function autoTranslateAttributes(): bool
{
    return false;
}
bash
php artisan vendor:publish --tag="translatable-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="translatable-config"