move into sonardesk
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
<?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]
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user