firstpoint-ch/eloquent-translatable

使Laravel Eloquent模型可翻译

1.1.0 2021-09-17 16:12 UTC

This package is auto-updated.

Last update: 2024-09-10 21:27:23 UTC


README

使您的Eloquent模型可翻译。

安装

您可以通过运行以下命令通过composer安装此包:

composer require firstpoint-ch/eloquent-translatable

配置模型

模型可以通过两种不同的方式进行翻译

  1. 数据库:它将翻译存储为数据库中的JSON
  2. 字典:它将键存储在全局的/resources/lang/[locale].json或任何特定的文件在/resources/lang/[locale]/[dictionary].php中,并从中检索翻译。

首先,您应该将任何数据库翻译字段存储为json列。此包提供了一个translatable宏,您可以快速查看哪些字段是可翻译的。使用字典模式的字段可以设置为string

Schema::create('products', function ($table) {
    $table->id();
    $table->translatable('name'); // Outputs $table->json('name');
    $table->string('category'); // Will be used as a dictionary
    $table->decimal('price');
    $table->timestamps();
})

然后,您应该将Translatable特质添加到模型中,并使用LocalizedDictionary转换属性

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,
        'description' => Localized::class,

        // Dictionary:
        //get value from /resources/lang/[locale].json
        'category' => Dictionary::class,

        // or get value from /resources/lang/[locale]/categories.php
        'category' => Dictionary::class.':categories',
    ];
}

基本示例

以下是对此包功能的一个快速预览,有关所有详细信息,请参阅我们的扩展文档

app()->setLocale('en');

// Set translation in the current locale
$product = Product::create(['name' => 'Product name']);

// Get translation in the current locale
echo $product->name; // Product name

// Get array in the current locale
dd($product->toArray()); // ['name' => 'Product name']

// Update the current locale
$product->update(['name' => 'New name']);

// Update a specific locale
$product->update(['name->fr' => 'Nom du produit']);

// Force a locale
echo $product->in('fr')->name; // Nom du produit

// Get raw value
dd($product->raw('name')); // ['en' => 'Product name', 'fr' => 'Nom du produit']
dd($product->in('*')->toArray()); // ['name' => ['en' => 'Product name', 'fr' => 'Nom du produit']]