PHP code example of flobbos / laravel-translatable-db

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

    

flobbos / laravel-translatable-db example snippets


Schema::create('languages', function (Blueprint $table) {
    $table->id();
    $table->string('locale')->unique();
    $table->string('name');
});

Schema::create('countries', function (Blueprint $table) {
    $table->id();
    $table->string('code')->unique();
    $table->timestamps();
});

Schema::create('country_translations', function (Blueprint $table) {
    $table->id();
    $table->foreignId('country_id')->constrained()->cascadeOnDelete();
    $table->foreignId('language_id')->constrained()->cascadeOnDelete();
    $table->string('name');

    $table->unique(['country_id', 'language_id']);
});

public $fallbackAttributes = ['name'];

'native_mode' => true,

namespace App\Models;

use Flobbos\TranslatableDB\TranslatableDB;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    use TranslatableDB;

    public $translatedAttributes = ['name'];
    public $fallbackAttributes = ['name'];

    protected $fillable = ['code'];
}

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CountryTranslation extends Model
{
    public $timestamps = false;

    protected $fillable = ['language_id', 'name'];
}

public $translationModel = CountryText::class;

$country = Country::where('code', 'gr')->first();

app()->setLocale('en');
echo $country->name; // Greece

app()->setLocale('de');
echo $country->name; // Griechenland

echo $country->getAttribute('name:2'); // Explicit language id

'use_db' => true,
'language_model' => App\Models\Language::class,
'locale_key' => 'language_id',
'locale_column' => 'locale',
'use_fallback' => true,
'fallback_locale_id' => 1,
'middleware_default' => false,
'to_array_always_loads_translations' => false,

'use_db' => false,
'language_array' => [
    'de' => ['name' => 'Deutsch', 'language_id' => 1],
    'en' => ['name' => 'English', 'language_id' => 2],
],

use Flobbos\TranslatableDB\Middleware\LanguageIdentification;

Route::middleware(LanguageIdentification::class)->group(function () {
    // translated routes
});

'middleware_default' => true,

namespace App\Models;

use Flobbos\TranslatableDB\Contracts\PolyTrans;
use Flobbos\TranslatableDB\TranslatableDB;
use Illuminate\Database\Eloquent\Model;

class Country extends Model implements PolyTrans
{
    use TranslatableDB;

    public $translationModel = Translation::class;

    protected $translationForeignKey = 'translatable';
}
bash
php artisan vendor:publish --provider="Flobbos\TranslatableDB\TranslatableDBServiceProvider"