Skip to content

Instantly share code, notes, and snippets.

@mohamedsabil83
Last active February 18, 2023 07:03
Show Gist options
  • Save mohamedsabil83/9c177e5fed984319663a92b7124cd285 to your computer and use it in GitHub Desktop.
Save mohamedsabil83/9c177e5fed984319663a92b7124cd285 to your computer and use it in GitHub Desktop.
A translatable trait for custom Filament page with spatie/laravel-translatable
<?php
namespace App\Filament\Traits;
use Filament\Resources\Pages\Concerns\HasActiveLocaleSwitcher;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
trait PageTranslatable
{
use HasActiveLocaleSwitcher;
protected function getActions(): array
{
return [
$this->getActiveLocaleSelectAction(),
];
}
public function getTranslatableLocales(): array
{
return config('filament-spatie-laravel-translatable-plugin.default_locales');
}
protected function handleRecordUpdate(Model $record, array $data): Model
{
$record->fill(Arr::except($data, $record->getTranslatableAttributes()));
collect(Arr::only($data, $record->getTranslatableAttributes()))->each(fn ($value, $key) => $record->setTranslation($key, $this->activeLocale, $value));
$record->save();
return $record;
}
public function fillForm(): void
{
$data = $this->getFormModel()->toArray();
if (empty($this->activeLocale)) {
$this->activeLocale = app()->getLocale();
}
foreach ($this->getFormModel()->getTranslatableAttributes() as $attribute) {
$data[$attribute] = $this->getFormModel()->getTranslation($attribute, $this->activeLocale);
}
$this->form->fill($data);
}
public function updatedActiveLocale(): void
{
$this->fillForm();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment