一个小型包,用于将模型中需要翻译的内容翻译,并按照应用区域向用户提供翻译字段

1.3.0 2022-02-14 13:36 UTC

This package is auto-updated.

Last update: 2024-09-14 19:14:52 UTC


README

Latest Version on Packagist Total Downloads Build Status StyleCI

一个非常简单的包,可以翻译Laravel模型中所需的一切,并以应用设置的语言向用户展示字段

安装

通过Composer

$ composer require thenonsensefactory/translate

使用方法

首先运行所需的迁移

$ php artisan migrate

现在您的数据库中有一个名为 'translations' 的新表

为了拥有可传输的模型,需要添加相关特性

<?php

    use TheNonsenseFactory\Translate\Traits\Translatable;

    class Article extends Model {
        
        use Translatable;

    }

然后您必须在 $translatable 数组中声明需要翻译的内容。这是一个强制性步骤。

<?php

    use TheNonsenseFactory\Translate\Traits\Translatable;

    class Article extends Model {
        
        use Translatable;

        protected $translatable = ['title', 'body'];

    }

要保存新的翻译,可以这样做

$article->translations()->create([
        'lang' => 'en',
        'field' => 'title',
        'text' => 'My Fancy Title'
    ]);

要为同一模型保存多个翻译(例如,在控制器的 store 方法中)可以使用 storeMultipleTranslations 方法

$translations = [
    'title' => [
        'it' => 'Il mio bel titolo',
        'en' => 'My fancy Title'
    ]
];

$article->storeMultipleTranslations($translations);

为了简单起见,如果找到已存在的翻译,此方法会更新记录。如果您想使用更具体或更易读的方法,可以使用

$article->createOrUpdateMultipleTranslations($translations);

当您访问已声明的可翻译字段时,就会发生魔法。如果当前应用语言中存在翻译,则包返回翻译,否则回退到模型表数据。

//If the App Locale is 'en'

$article->title //Provide the en translation (if present)

//If the App locale is 'it'

$article->title //Provide the it translation (if present)

//If the App locale is 'de' and the translation does not exsist

$article->title //Provide the title from the Articles Table

您有一个查询范围和一个有用的帮助方法

$article->translations()->currentLang() //Provide all the translations in the current App Locale set

$article->updateOrCreateTranslation($array) // Update a translation if present or create a new one in the current Language set in App Locale

您需要提供给 updateOrCreateTranslation 方法的数组必须是以下形状

field => text

例如

['title' => 'My Fancy Title Updated']

变更日志

请参阅 变更日志 了解最近的变化。

贡献

请参阅 contributing.md 了解详细信息以及待办事项列表。

安全

如果您发现任何安全相关的问题,请通过电子邮件联系作者,而不是使用问题跟踪器。

鸣谢

许可证

许可证。请参阅 许可证文件 了解更多信息。