I use Voyager admin interface (v.1.4) for Laravel (v8.0). Voyager supports multiple languages (official documentation: https://voyager-docs.devdojo.com/v/1.4-1/core-concepts/multilanguage).
I have this relationship:
- Process belongsToMany WorkMachine
- Process hasMany Product
Process model:
JavaScript
x
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use TCGVoyagerTraitsTranslatable;
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:
JavaScript
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use TCGVoyagerTraitsTranslatable;
class WorkMachine extends Model
{
use Translatable;
protected $translatable = ['name', 'meta_description', 'description'];
Product model:
JavaScript
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use TCGVoyagerTraitsTranslatable;
class Product extends Model
{
use Translatable;
protected $translatable = ['name'];
In my controller:
JavaScript
$process = AppModelsProcess::where('slug', $processSlug)
->with('get_workmachine')
->with('get_products')
->firstOrFail()->translate(app()->getLocale());
The problem is: the Process translatable text works, the output language depends from app()->getLocale()
. But the workmachine texts and products texts aren’t translated.
I try also to use:
JavaScript
->with(['get_workmachine' => function ($query) { $query->withTranslation('de'); }])
But it isn’t translated.
Any solutions to translate the relationship?
Advertisement
Answer
I have found a possible solution! In my .blade file, instead of:
JavaScript
@foreach(json_decode($process->get_workmachine) as $workmachine)
@endforeach
I added ->translate(app()->getLocale())
:
JavaScript
@foreach(json_decode($process->get_workmachine->translate(app()->getLocale())) as $workmachine)
@endforeach
This works!