Models can be translated in two ways:
/resources/lang/[locale].json
or any specific file in /resources/lang/[locale]/[dictionary].php
.First you should store any database translated field as a json
column. This package provides a translatable
macro so you can quickly see which fields are translatable. Fields using the dictionary mode can be set to string
.
Schema::create('products', function ($table) {
$table->id();
$table->translatable('name'); // Outputs $table->json('name');
$table->string('category'); // Will use the dictionary mode
$table->decimal('price');
$table->timestamps();
})
Then you can add the Translatable
trait to the model and cast attributes using Localized
or Dictionary
use FirstpointCh\Translatable\Casts\Dictionary;
use FirstpointCh\Translatable\Casts\Localized;
use FirstpointCh\Translatable\Traits\Translatable;
class Product extends Model
{
use Translatable;
protected $casts = [
// Database
'name' => Localized::class,
// Dictionary: get value from /resources/lang/[locale].json
'category' => Dictionary::class,
];
}
You can specify the dictionary by appending the name as a parameter.
class Product extends Model
{
protected $casts = [
// Will get value from /resources/lang/[locale]/categories.php
'category' => Dictionary::class.':categories',
];
}