
在使用 Laravel Voyager 管理后台时,实现 relationships 的多语言翻译是一个常见的需求。本文将介绍如何在 Voyager 中正确配置和使用 Translatable trait,以确保在处理 belongsToMany 和 hasMany 等关系时,能够根据当前应用语言环境显示翻译后的数据。通过示例代码和详细步骤,帮助开发者解决关系数据无法翻译的问题,并提供一种在 Blade 模板中正确访问翻译后关系数据的方法。
首先,确保你的模型使用了 TCG\Voyager\Traits\Translatable trait,并且正确定义了 $translatable 属性。这个属性是一个数组,包含了需要进行翻译的字段。
例如,对于 Process、WorkMachine 和 Product 模型,你的配置应该如下:
Process Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use TCG\Voyager\Traits\Translatable;
class Process extends Model
{
use Translatable;
protected $translatable = ['name', 'meta_description', 'description'];
public function get_workmachine() {
return $this->belongsToMany(WorkMachine::class, 'process_workmachine');
}
public function get_products() {
return $this->hasMany(Product::class, 'process_product');
}
}WorkMachine Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use TCG\Voyager\Traits\Translatable;
class WorkMachine extends Model
{
use Translatable;
protected $translatable = ['name', 'meta_description', 'description'];
}Product Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use TCG\Voyager\Traits\Translatable;
class Product extends Model
{
use Translatable;
protected $translatable = ['name'];
}在控制器中,你需要确保获取到的数据已经进行了翻译。可以直接在查询结果上调用 translate() 方法,并传入当前应用的 locale。
$process = App\Models\Process::where('slug', $processSlug)
->with('get_workmachine')
->with('get_products')
->firstOrFail()->translate(app()->getLocale());尝试使用 -youjiankuohaophpcnwith(['get_workmachine' => function ($query) { $query->withTranslation('de'); }]) 预加载翻译可能不会直接生效,因为关系本身可能没有被正确翻译。
在 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解释:
通过正确配置模型中的 Translatable trait,并在控制器和 Blade 模板中合理使用 translate() 方法,可以有效地实现 Voyager 中 relationships 的多语言翻译。关键在于理解何时以及如何对关系数据进行翻译,并确保你的代码能够正确访问翻译后的属性。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号