
在使用 Laravel Voyager 管理后台时,实现 relationships 的多语言翻译是一个常见的需求。本文将介绍如何在 Voyager 中正确配置和使用 Translatable trait,以确保在处理 belongsToMany 和 hasMany 等关系时,能够根据当前应用语言环境显示翻译后的数据。通过示例代码和详细步骤,帮助开发者解决关系数据无法翻译的问题,并提供一种在 Blade 模板中正确访问翻译后关系数据的方法。
模型配置:使用 Translatable trait
首先,确保你的模型使用了 TCGVoyagerTraitsTranslatable trait,并且正确定义了 $translatable 属性。这个属性是一个数组,包含了需要进行翻译的字段。
例如,对于 Process、WorkMachine 和 Product 模型,你的配置应该如下:
Process Model:
belongsToMany(WorkMachine::class, 'process_workmachine'); } public function get_products() { return $this->hasMany(Product::class, 'process_product'); }}
WorkMachine Model:
<?phpnamespace AppModels;use IlluminateDatabaseEloquentModel;use TCGVoyagerTraitsTranslatable;class WorkMachine extends Model{ use Translatable; protected $translatable = ['name', 'meta_description', 'description'];}
Product Model:
<?phpnamespace AppModels;use IlluminateDatabaseEloquentModel;use TCGVoyagerTraitsTranslatable;class Product extends Model{ use Translatable; protected $translatable = ['name'];}
控制器中的数据获取
在控制器中,你需要确保获取到的数据已经进行了翻译。可以直接在查询结果上调用 translate() 方法,并传入当前应用的 locale。
$process = AppModelsProcess::where('slug', $processSlug) ->with('get_workmachine') ->with('get_products') ->firstOrFail()->translate(app()->getLocale());
尝试使用 ->with([‘get_workmachine’ => function ($query) { $query->withTranslation(‘de’); }]) 预加载翻译可能不会直接生效,因为关系本身可能没有被正确翻译。
Blade 模板中的正确用法
在 Blade 模板中,访问 relationship 时,需要对 relationship 的结果进行翻译。如果直接访问 relationship 返回的是一个集合或对象,你需要对集合中的每个元素或对象调用 translate() 方法。
错误示例:
@foreach(json_decode($process->get_workmachine) as $workmachine) ... ...@endforeach
正确示例:
@foreach($process->get_workmachine as $workmachine) {{ $workmachine->translate(app()->getLocale())->name }}@endforeach
或者,如果需要将整个集合转换为 JSON,再在前端解析,也需要先对集合进行翻译:
@foreach(json_decode($process->get_workmachine->translate(app()->getLocale())) as $workmachine) ... ...@endforeach
解释:
$process->get_workmachine 返回的是 WorkMachine 模型的集合。$workmachine->translate(app()->getLocale()) 对单个 WorkMachine 模型实例进行翻译,返回翻译后的实例。->name 访问翻译后的 WorkMachine 模型的 name 属性。
注意事项
确保你的数据库中已经存在相应语言的翻译数据。检查 config/voyager.php 中的 multilingual.enabled 是否设置为 true,以及 multilingual.default 是否设置为你的默认语言。如果仍然无法正常显示翻译,尝试清除缓存:php artisan cache:clear 和 php artisan config:cache。如果使用了自定义的 relationship 方法(如 get_workmachine()),请确保这些方法返回的是 Eloquent relationship 对象,而不是直接返回数据。
总结
通过正确配置模型中的 Translatable trait,并在控制器和 Blade 模板中合理使用 translate() 方法,可以有效地实现 Voyager 中 relationships 的多语言翻译。关键在于理解何时以及如何对关系数据进行翻译,并确保你的代码能够正确访问翻译后的属性。
以上就是Voyager Relationships 的多语言翻译实现的详细内容,更多请关注php中文网其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1321728.html
微信扫一扫
支付宝扫一扫