37 lines
1.2 KiB
PHP
37 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace Modules\Localization\Concerns;
|
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
|
use Modules\Localization\Models\Locale;
|
|
use Modules\Localization\Models\LocalizedContent;
|
|
|
|
trait HasTranslations
|
|
{
|
|
public function translations(): MorphMany
|
|
{
|
|
return $this->morphMany(LocalizedContent::class, 'translatable');
|
|
}
|
|
|
|
public function translated(string $field, ?string $locale = null, mixed $fallback = null): mixed
|
|
{
|
|
$locale ??= app()->getLocale();
|
|
$translation = $this->translations->first(fn (LocalizedContent $item): bool => $item->field === $field && $item->locale?->code === $locale);
|
|
if ($translation && filled($translation->value)) {
|
|
return $translation->value;
|
|
}
|
|
|
|
return $fallback ?? $this->getAttribute($field);
|
|
}
|
|
|
|
public function setTranslation(string $field, string $localeCode, ?string $value, ?int $userId = null): LocalizedContent
|
|
{
|
|
$locale = Locale::query()->where('code', $localeCode)->firstOrFail();
|
|
|
|
return $this->translations()->updateOrCreate(
|
|
['locale_id' => $locale->id, 'field' => $field],
|
|
['value' => $value, 'updated_by' => $userId]
|
|
);
|
|
}
|
|
}
|