PHP code example of esign / laravel-underscore-translatable

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

    

esign / laravel-underscore-translatable example snippets


use Esign\UnderscoreTranslatable\UnderscoreTranslatable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use UnderscoreTranslatable;

    public $translatable = ['title'];
}

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title_nl')->nullable();
    $table->string('title_fr')->nullable();
    $table->string('title_en')->nullable();
});

$post->title
$post->getTranslation('title')

$post->title_nl
$post->getTranslation('title', 'nl')

$post->title_en = 'Your first translation';
$post->title_nl = '';
$post->title_fr = null;

$post->hasTranslation('title', 'en'); // returns true
$post->hasTranslation('title', 'nl'); // returns false
$post->hasTranslation('title', 'fr'); // returns false

$post->title_en = 'Your first translation';
$post->title_nl = null;
$post->getTranslation('title', 'nl', true); // returns 'Your first translation'
$post->getTranslation('title', 'nl', false); // returns null

$post->title_en = 'Your first translation';
$post->title_nl = null;
$post->getTranslationWithFallback('title', 'nl'); // returns 'Your first translation'
$post->getTranslationWithoutFallback('title', 'nl'); // returns null

$post->title = 'Your first translation';

Post::create([
    'title' => 'Your first translation',
]);

$post->setTranslation('title', 'en', 'Your first translation');
$post->setTranslation('title', 'nl', 'Jouw eerste vertaling');

$post->setTranslations('title', [
    'en' => 'Your first translation',
    'nl' => 'Jouw eerste vertaling',
]);

Post::create([
    'title' => [
        'en' => 'Your first translation',
        'nl' => 'Jouw eerste vertaling',
    ],
]);

$post->setTranslation('title', 'en', 'Your first translation');
$post->save();

public function getTitleAttribute($value): string
{
    return ucfirst($value);
}

public function setTitleAttribute($value, $locale): void
{
    $this->attributes['title_' . $locale] = strtolower($value);
}