PHP code example of tabaoman / laravel-translation

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

    

tabaoman / laravel-translation example snippets


return [
    /*
     * The table that restores the multi-language texts
     * NOTES: Avoid to have any timestamp field.
     *        If you need to record the created/updated time, use 'model' as following.
     */
    'table' => 't_language_translate',
    
    /*
     * An example helper model.
     * It has a higher priority than 'table' if it is not commented out.
     */
    //'model' => \Tabaoman\Translation\Models\LanguageTranslate::class
];

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Tabaoman\Translation\Translation;
class Store extends Model
{
    use Translation;
    protected $casts = ['id' => 'string']; // Sometimes you need this cast
    
    protected $translations = [
        'name' => 'STORE_NAME' // attribute => text code
        // 'name' => ['code' => 'STORE_NAME'], // Or associate like this
        // 'name' => ['code' => 'STORE_NAME', 'my_key' => 'my_value'] // You can add custom key-value pair for other uses.
    ];
    
    // ...
}

$store = Store::first();
echo $store->name; // Get with default language setting (App::getLocale())

echo $store->getTranslation('name', 'en'); // Get its English name
App::setLocale('en');
echo $store->name; // Or get its English name after explicitly set app locale

$store = Store::first();
echo $store->name; // 苹果商店

$store->setTranslation('name', 'Apple store', 'en'); // Directly save the English name
App::setLocale('en');
$store->name = 'Apple store'; // Or set its English name after explicitly set app locale
$store->save(); // Optional if there is no mutator for 'name'

$store = Store::first();
echo $store->name; // Apple store

App::setLocale('zh_CN');
echo $store->name; // 苹果商店


    protected $translations = [
        'name' => 'STORE_NAME' // attribute => text code
        'name_english' => ['code' => 'STORE_NAME', 'locale' => 'en'],  // You are free to define your own language code.
    ];

$store = Store::first();
echo $store->name;         // 苹果商店
echo $store->name_english; // Apple store