Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
使用自动加载翻译在 Laravel 中构建多态可翻译模型_创想鸟

使用自动加载翻译在 Laravel 中构建多态可翻译模型

使用自动加载翻译在 laravel 中构建多态可翻译模型

处理多语言内容时,将翻译存储在 json 列中通常比每个属性的单独行更有效。这种方法将翻译整合到单个列中,简化了数据管理和检索。

设置翻译系统

我们将增强翻译模型和表,以使用 json 列来存储翻译。这将涉及更新表架构并修改 translatable 特征以处理 json 数据。

第 1 步:创建翻译表迁移

如果翻译表尚不存在,则创建一个新的迁移:

php artisan make:migration create_translations_table

第2步:定义表结构

在database/migrations中打开生成的迁移文件。对于新表,定义如下:

use illuminatedatabasemigrationsmigration;use illuminatedatabaseschemablueprint;use illuminatesupportfacadesschema;class createtranslationstable extends migration{    public function up()    {        schema::create('translations', function (blueprint $table) {            $table->id();            $table->string('locale'); // stores the locale, e.g., 'en', 'fr'            $table->string('translatable_type'); // stores the related model type, e.g., 'post', 'product'            $table->unsignedbiginteger('translatable_id'); // stores the id of the related model            $table->json('translations'); // stores all translations as a json object            $table->timestamps();        });    }    public function down()    {        schema::dropifexists('translations');    }}

第 3 步:运行迁移
将迁移应用到您的数据库:

php artisan migrate

第四步:创建翻译模型

接下来,创建翻译模型来处理多态关系:

php artisan make:model translation

在translation模型中,定义多态关系:

class translation extends model{    protected $fillable = ['locale', 'translatable_type', 'translatable_id', 'translations'];    protected $casts = [        'translations' => 'array',    ];    public function translatable()    {        return $this->morphto();    }}

使用 json 存储实现可翻译特征

为了使翻译处理可在多个模型中重用,我们将创建一个 translatable 特征,它将根据用户选择的区域设置自动加载翻译内容。此外,如果所选语言环境没有可用的翻译,我们将添加一个后备机制来从默认语言环境加载内容。

第 1 步:使用 json 处理创建可翻译特征

namespace apptraits;use appmodelstranslation;use illuminatesupportfacadesapp;trait translatable{    public static function boottranslatable()    {        static::retrieved(function ($model) {            $model->loadtranslations();        });    }    public function translations()    {        return $this->morphmany(translation::class, 'translatable');    }    public function loadtranslations()    {        $locale = app::getlocale();        $defaultlocale = config('app.default_locale', 'en'); // fallback to the default locale        // try to load translations for the current locale        $translation = $this->translations()->where('locale', $locale)->first();        if (!$translation && $locale !== $defaultlocale) {            // if no translations are found for the current locale, fallback to the default locale            $translation = $this->translations()->where('locale', $defaultlocale)->first();        }        if ($translation) {            $translations = $translation->translations;            foreach ($translations as $key => $value) {                $this->{$key} = $value;            }        }    }    public function addtranslations(array $translations, $locale = null)    {        $locale = $locale ?? app::getlocale();        return $this->translations()->updateorcreate(            ['locale' => $locale],            ['translations' => $translations]        );    }}

第 2 步:将可翻译特征应用于您的模型
将 translatable 特征添加到任何需要翻译支持的模型中。

namespace appmodels;use apptraitstranslatable;use illuminatedatabaseeloquentmodel;class post extends model{    use translatable;    protected $fillable = ['title', 'content'];}

示例:创建翻译模型

将翻译添加为 json 对象:

$post = post::create(['title' => 'default title', 'content' => 'default content']);// adding translations$post->addtranslations([    'title' => 'hello world',    'content' => 'welcome to our website'], 'en');$post->addtranslations([    'title' => 'bonjour le monde',    'content' => 'bienvenue sur notre site web'], 'fr');

检索翻译模型

当您检索 post 模型时,它将根据当前语言环境自动加载翻译后的内容,或者在必要时回退到默认语言环境:

app::setlocale('fr');$post = post::find(1);echo $post->title; // displays "bonjour le monde" if french translation existsapp::setlocale('es');$post = post::find(1);echo $post->title; // displays "hello world" as it falls back to the english translation

在视图中显示翻译内容

在 blade 视图中,您可以像任何其他模型属性一样显示翻译的内容:

{{ $post->title }}

{{ $post->content }}

结论

通过使用 json 列来存储翻译并实现回退机制,您可以简化 laravel 应用程序中多语言内容的管理。这种方法将翻译整合到单个列中,简化了数据处理并使您的代码库更易于维护。无论您是构建博客、电子商务网站还是任何多语言应用程序,此方法都能确保流畅高效的用户体验。

尽情享受!

以上就是使用自动加载翻译在 Laravel 中构建多态可翻译模型的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1244416.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
如何通过验证令牌在 PHP 中设置电子邮件验证:完整指南
上一篇 2025年12月9日 16:49:46
php后端包括哪些
下一篇 2025年12月9日 16:49:59

相关推荐

发表回复

登录后才能评论
关注微信