PHP code example of jetcod / laravel-model-translation

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

    

jetcod / laravel-model-translation example snippets


return [
    'database' => [
        'prefix' => env('TRANSLATION_TABLE_PREFIX', 'lt_'),
        'table_name' => env('TRANSLATION_TABLE_NAME', 'translations'),
    ],
];

use Jetcode\Laravel\Translation\Traits\HasTranslations;

class Post extends Model
{
    use HasTranslations;

    protected const TRANSLATABLE_ATTRIBUTES = ['title', 'content'];
}

use Jetcode\Laravel\Translation\Traits\HasTranslations;

class Post extends Model
{
    use HasTranslations;

    protected function getTranslatableAttributes()
    {
        return ['title', 'content'];
    }
}

// Create a new post with translations
$post = Post::create([
    'title' => 'Hello World',
    'content' => 'This is a post',
]);

// Create a new translation for the post
$post->translation()->saveMany([
    new Translation([
        'locale' => 'fr_FR',
        'key'    => 'title',
        'value'  => 'Bonjour le monde',
    ]),
    new Translation([
        'locale' => 'fr_FR',
        'key'    => 'content',
        'value'  => 'Ceci est un article',
    ]),
]);

$post = Post::find(123);
var_dump($post->title);     // "Hello World"

app()->setLocale('fr_FR');
var_dump($post->title);     // "Bonjour le monde"

var_dump($post->withLocale('fr_FR')->title); // "Bonjour le monde"

// Current locale is reset to default afterwards
var_dump($post->title); // "Hello World"
bash
php artisan vendor:publish --tag=translation-config
php artisan vendor:publish --tag=translation-migrations
bash
php artisan migrate