lechihuy/laratrans

此包已被弃用,不再维护。未建议替代包。

支持Laravel的多语言资源。

v1.0.0 2021-10-07 15:05 UTC

This package is auto-updated.

Last update: 2022-01-10 16:31:09 UTC


README

Total Downloads Latest Stable Version License

Laratrans

支持Laravel的多语言资源。

文档

安装

composer require lechihuy/laratrans

安装包成功后,请在您的项目目录中打开终端并运行以下命令

php artisan laratrans:install

配置

您可以在 app/config/translatable.php 中配置此包,请阅读以获取更多详细信息。

数据库

...

模型

假设,您需要对 Post 模型应用翻译。

首先,在 Post 模型文件中使用以下 Laratrans\Translatable trait

<?php

use Laratrans\Translatable;

class Post extends Model
{
    use Translatable;
}

接下来,打开您的终端并运行以下命令以创建翻译模型

php artisan make:model Translation/PostTranslation

Translation 命名空间必须与配置文件中的 translation_namespace 相对应。此外,翻译模型名称的后缀必须是 Translation

Post 模型需要翻译 titledescription 列。您只需在这个模型中声明 translatedAttributes 属性。

class Post extends Model
{
    /**
     * The columns are translatable.
     * 
     * @var string[]
    */
    public array $translatedAttributes = ['title', 'description'];
    
    /**
     * The relationships that should always be loaded.
     *
     * @var array
     */
    protected $with = ['translations'];
}

您需要声明预加载,以便它能够工作。此包提供了两种预加载方式:translationstranslation

如果您使用 translations 预加载序列化可翻译模型,则响应可以如下所示

{
    "id": 1,
    "created_at": "2021-10-07T06:55:46.000000Z",
    "updated_at": "2021-10-07T06:55:46.000000Z",
    "title": "Xin chào thế giới",
    "description": "Đây là bài viết đầu tiên",
    "translations": [
        {
            "post_id": 1,
            "locale": "vi",
            "title": "Xin chào thế giới",
            "description": "Đây là bài viết đầu tiên"
        },
        {
            "post_id": 1,
            "locale": "en",
            "title": "Hello world",
            "description": "This is the first post"
        }
    ]
}

否则,如果您使用 translation 预加载,则响应将不包含 translations 属性。

如果您想要隐藏一些冗余属性,可以通过模型中的 $hidden 属性来实现。

class Post extends Model
{
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['post_id'];
}

许可证

Laratrans 是开源软件,许可协议为 MIT 协议