Last active
February 18, 2023 07:03
-
-
Save mohamedsabil83/9c177e5fed984319663a92b7124cd285 to your computer and use it in GitHub Desktop.
A translatable trait for custom Filament page with spatie/laravel-translatable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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