I'm having trouble translating a pivot column.
I've been trying all day to add this translation but it still doesn't work.
I'm using the package: https://github.com/Astrotomic/laravel-translatable
Plain tables work fine, but pivot doesn't.
My code (the naming was quick, as the code will work, I'm going to refactor it):
class Offer extends Model implements TranslatableContract
use HasFactory, Translatable;
public array $translatedAttributes = [
'name',
'description'
];
public function attributes(): BelongsToMany
{
return $this->belongsToMany(Attribute::class, 'attribute_offer')->using(AttributeOffer::class)->withTimestamps();
}
class Attribute extends Model implements TranslatableContract
{
use HasFactory, Translatable;
public array $translatedAttributes = [
'name',
];
public function values(): BelongsToMany
{
return $this->belongsToMany(Offer::class, 'attribute_offer', 'attribute_id', 'offer_id')->using(AttributeOffer::class);
}
class AttributeOffer extends Pivot implements TranslatableContract
{
use Translatable;
public $incrementing = true;
public array $translatedAttributes = [
'content',
];
protected $fillable = [
'attribute_id',
'offer_id',
];
}
class AttributeOfferTranslation extends Model
{
protected $table = 'attribute_offer_translations';
public $timestamps = false;
protected $fillable = [
'content',
];
}
class OfferController extends Controller
{
private function updateAttributeValues($offer, $attributes)
{
foreach ($attributes as $slug => $values) {
$pivot = $offer->attributes()->whereSlug($slug)->first()->pivot;
foreach ($values as $locale => $value) {
$pivot->translate($locale)->content = $value;
}
}
}
The structure of the attributes is:
[
'test' =>[
'en' => 'test',
'es' => 'test',
'de' => 'test',
],
'test2' =>[
'en'=> 'test',
'es'=> 'test',
'de' => 'test',
],
]
Unfortunately pivot->translate() always returns null.
Also, when I manually add transactions to the database, it does not display it.
I will be very grateful for help with this translation.
Okay, I fixed it like this, only I have to pass id instead of slugs.
class Offer extends Model implements TranslatableContract
{
...
public function attributeValues(): HasMany
{
return $this->hasMany(AttributeOffer::class);
}
}
class AttributeOffer extends Pivot implements TranslatableContract
{
...
protected $translationForeignKey = 'attribute_offer_id';
...
}
private function updateAttributeValues($offer, $attributes)
{
foreach ($attributes as $id => $values) {
$offer->attributeValues()->whereAttributeId($id)->first()->update($values);
}
}