PHP code example of roundly-consulting / translatable-for-laravel

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

    

roundly-consulting / translatable-for-laravel example snippets


use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use RoundlyConsulting\Translatable\Concerns\HasTranslations;
use RoundlyConsulting\Translatable\Contracts\Translatable;

Schema::create('topics', function (Blueprint $table): void {
    $table->id();
    $table->translatable('name');   // a jsonb column
    $table->timestamps();
});

final class Topic extends Model implements Translatable
{
    use HasTranslations;

    protected $fillable = ['name'];

    /** @var list<string> */
    public array $translatable = ['name'];
}

$topic = Topic::create(['name' => ['en' => 'Investing']]);

app()->setLocale('sk');
$topic->name;                                    // 'Investing' — falls back to `en`
$topic->missingLocales('name');                  // ['sk']

$topic->setTranslation('name', 'sk', 'Investovanie')->save();
$topic->name;                                    // 'Investovanie'
$topic->getTranslations('name');                 // ['en' => 'Investing', 'sk' => 'Investovanie']

use RoundlyConsulting\Translatable\Facades\Translatable;

Translatable::usingLocale('en', fn (): string => $topic->name);                     // 'Investing'
$topic->setTranslations('name', Translatable::fromInput($request->input('name')));  // replaces the map with the form's locales