### LocaleSwitcher Setup PHP Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/LocaleSwitcher.md Initializes the action during setup, configuring the label and populating locale options. ```php protected function setUp(): void { parent::setUp(); $this->setLabel(trans('filament-spatie-laravel-translatable-plugin::actions.active_locale.label')); $this->setTranslatableLocaleOptions(); } ``` -------------------------------- ### Dependency Injection Examples Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Demonstrates how models are resolved via the container and how to access the plugin instance. ```php $model = app($modelClass); // Resolved via container ``` ```php filament('spatie-laravel-translatable') // From container ``` -------------------------------- ### Basic Plugin Setup Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/configuration.md Configure the plugin with a set of default locales in your Filament panel provider file. ```php use Filament\SpatieLaravelTranslatablePlugin; use Filament\Panel; public function panel(Panel $panel): Panel { return $panel ->plugin( SpatieLaravelTranslatablePlugin::make() ->defaultLocales(['en', 'es', 'fr', 'de']) ); } ``` -------------------------------- ### Install Filament Spatie Translatable Plugin Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/README.md Install the plugin using Composer. The -W flag ensures all dependencies are updated. ```bash composer require filament/spatie-laravel-translatable-plugin:"^3.2" -W ``` -------------------------------- ### Configure Plugin Instance Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Example of how to configure the Spatie Laravel Translatable Plugin using its fluent interface. ```php SpatieLaravelTranslatablePlugin::make()->... ``` -------------------------------- ### Type Hint Examples Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Illustrates various type hints used within the plugin for different data structures and types. ```php // Array of strings (locale codes) array // Array of key-value pairs (data) array // Closure for locale label generation Closure(string $locale, ?string $displayLocale): ?string // Eloquent model Model // Query builder Builder // Class string/FQCN class-string ``` -------------------------------- ### Install Spatie Laravel Translatable Plugin Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/IMPLEMENTATION_GUIDE.md Install the Spatie Laravel Translatable plugin using Composer. Ensure you are using the correct version for Filament 3.x. ```bash composer require filament/spatie-laravel-translatable-plugin:"^3.2" -W ``` -------------------------------- ### Next Steps Options Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/00_START_HERE.md Presents different paths for engaging with the documentation based on user goals, ranging from a quick start to a deep dive or reference-only approach. ```text Option A: Quick Start (30 min) └─ Read README.md now Then refer to files as needed Option B: Guided Setup (2 hours) └─ Follow IMPLEMENTATION_GUIDE.md completely Then use other files for customization Option C: Deep Dive (3 hours) └─ Read in order: README → IMPLEMENTATION → architecture Then explore API reference files Option D: Reference Only (ongoing) └─ Use INDEX.md to find what you need EXPORTS_REFERENCE.md to find methods API files for details ``` -------------------------------- ### Plugin Level Configuration and Getting Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Chainable methods for configuring default locales and locale label callbacks, and methods for retrieving locale information at the plugin level. ```php public function defaultLocales(?array $defaultLocales = null): static public function getLocaleLabelUsing(?Closure $callback): static ``` ```php public function getDefaultLocales(): array public function getLocaleLabel(string $locale, ?string $displayLocale = null): ?string ``` -------------------------------- ### Instantiate SpatieLaravelTranslatableContentDriver Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/SpatieLaravelTranslatableContentDriver.md The driver is automatically instantiated by resource pages with the active locale. This example shows manual instantiation for testing or specific use cases. ```php use Filament\SpatieLaravelTranslatableContentDriver; $driver = new SpatieLaravelTranslatableContentDriver('en'); ``` -------------------------------- ### Locale Options Generation Example Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/LocaleSwitcher.md Illustrates the structure of the locale options array generated by the `HasTranslatableLocaleOptions` trait. ```php trait HasTranslatableLocaleOptions { public function setTranslatableLocaleOptions(): static } ``` ```php [ 'en' => 'English', 'es' => 'Español', 'fr' => 'Français', 'de' => 'Deutsch', ] ``` -------------------------------- ### Basic Filament Resource with Translatable Trait Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourceTranslatable.md Demonstrates the basic setup of a Filament resource using the Translatable trait. This includes defining the model and basic form and table schemas. ```php use Filament\Resources\Resource; use Filament\Resources\Concerns\Translatable; use Filament\Forms; use Filament\Tables; class BlogPostResource extends Resource { use Translatable; protected static ?string $model = BlogPost::class; public static function form(Forms\Form $form): Forms\Form { return $form ->schema([ Forms\Components\TextInput::make('title') ->required(), Forms\Components\Textarea::make('content') ->required(), Forms\Components\TextInput::make('slug'), ]); } public static function table(Tables\Table $table): Tables\Table { return $table ->columns([ Tables\Columns\TextColumn::make('title') ->searchable(), Tables\Columns\TextColumn::make('content') ->limit(50), ]) ->filters([ // ]); } } ``` -------------------------------- ### Get Plugin Instance Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Retrieve the plugin instance using Filament's service container. ```php filament('spatie-laravel-translatable') ``` -------------------------------- ### Plugin Configuration Chain Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Shows how to configure the Spatie Laravel Translatable plugin using a chainable method interface. Configuration is typically called during plugin setup. ```php SpatieLaravelTranslatablePlugin::make() ->defaultLocales(['en', 'es', 'fr']) // ✓ Chainable ->getLocaleLabelUsing(function($locale) {...}) // ✓ Chainable // ->register() Called by framework // ->boot() Called by framework ``` -------------------------------- ### Configure Translatable Resource for Simple Pages Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/IMPLEMENTATION_GUIDE.md Example of setting up a Filament resource to use the Translatable trait for simple manage pages. Ensure both the resource and its page use the trait. ```php use Filament\Actions; use Filament\Resources\Pages\ManageRecords; use Filament\Resources\Resource; use Spatie\Translatable\HasTranslations; // app/Filament/Resources/CategoryResource.php class CategoryResource extends Resource { use Translatable; // ... form and table public static function getPages(): array { return [ 'index' => Pages\ManageCategories::route('/'), ]; } } // app/Filament/Resources/CategoryResource/Pages/ManageCategories.php class ManageCategories extends ManageRecords { use ManageRecords\Concerns\Translatable; protected static string $resource = CategoryResource::class; protected function getHeaderActions(): array { return [ Actions\CreateAction::make(), Actions\LocaleSwitcher::make(), ]; } } ``` -------------------------------- ### Customize Locale Labels with Custom Logic Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/IMPLEMENTATION_GUIDE.md This example shows how to use the `getLocaleLabelUsing` method to provide custom labels, including flags, for each locale in the switcher. It maps locale codes to displayable strings. ```php ->plugin( SpatieLaravelTranslatablePlugin::make() ->defaultLocales(['en', 'es', 'fr', 'de', 'ja']) ->getLocaleLabelUsing(function (string $locale) { $labels = [ 'en' => '🇬🇧 English', 'es' => '🇪🇸 Español', 'fr' => '🇫🇷 Français', 'de' => '🇩🇪 Deutsch', 'ja' => '🇯🇵 日本語', ]; return $labels[$locale] ?? null; }) ) ``` -------------------------------- ### Table Column Search Integration Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Example of using `searchable()` on a TextColumn to enable translation-aware search on the active locale's content. ```php Tables\Columns\TextColumn::make('title') ->searchable() // Searches active locale's translation ``` -------------------------------- ### Database Migration with JSON Column Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/configuration.md Example database migrations for storing translatable attributes in JSON columns. This can be done per attribute or in a single 'translations' column. ```php Schema::create('blog_posts', function (Blueprint $table) { $table->id(); $table->json('title'); // Stores: {"en": "...", "es": "...", ...} $table->json('content'); // Stores: {"en": "...", "es": "...", ...} $table->json('slug'); $table->unsignedBigInteger('author_id'); $table->timestamps(); }); ``` ```php Schema::create('blog_posts', function (Blueprint $table) { $table->id(); $table->json('translations'); // Stores all translatable attrs $table->unsignedBigInteger('author_id'); $table->timestamps(); }); ``` -------------------------------- ### Documentation Statistics Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/00_START_HERE.md Provides an overview of the documentation's scope, including the number of files, lines, words, code examples, classes, traits, methods, and configuration options. ```text Total Files: 12 markdown files Total Lines: ~5,000 lines Total Words: ~25,000 words Code Examples: 100+ examples Classes: 4 classes Traits: 10+ traits Methods: 50+ methods Configuration Keys: 10+ options ``` -------------------------------- ### Basic Relation Manager Setup with Locale Switcher Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/RelationManagerTranslatable.md Configures a relation manager to support translatable content and includes a locale switcher in the header actions. This enables users to switch between languages within the relation manager. ```php use Filament\Resources\RelationManagers\RelationManager; use Filament\Resources\RelationManagers\Concerns\Translatable; use Filament\Tables; use Filament\Tables\Table; class BlogPostsRelationManager extends RelationManager { use Translatable; protected static string $relationship = 'blogPosts'; public function table(Table $table): Table { return $table ->columns([ Tables\Columns\TextColumn::make('title'), Tables\Columns\TextColumn::make('content'), ]) ->headerActions([ Tables\Actions\LocaleSwitcher::make(), ]); } } ``` -------------------------------- ### Example of Handling Translations During Creation Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Illustrates how form data for different locales is managed during the creation process. When switching locales, data for the previous locale is stored, and the new locale's data is displayed for editing before persistence. ```php use Filament\Resources\Pages\CreateRecord; class CreateBlogPost extends CreateRecord { use Translatable; // Form field for title (translatable) // When user fills in 'en' title, clicks "Switch to Es", // the 'en' title is stored in $otherLocaleData['en'], // 'es' title is displayed and edited, // On save, both are persisted } ``` -------------------------------- ### Reactive Relation Manager Setup Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/RelationManagerTranslatable.md Set up a relation manager for reactive locale synchronization by adding the `#[Reactive]` attribute to the `activeLocale` property. This ensures the relation manager's locale automatically matches the parent resource page's locale. ```php use Livewire\Attributes\Reactive; class BlogPostsRelationManager extends RelationManager { use Translatable; #[Reactive] public ?string $activeLocale = null; // <-- Add #[Reactive] public function table(Table $table): Table { return $table ->headerActions([ // LocaleSwitcher not needed ]); } } ``` -------------------------------- ### Configure Default Locales for the Plugin Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/IMPLEMENTATION_GUIDE.md Example of configuring the default locales for the Spatie Laravel Translatable plugin using a fluent API. This sets the available languages for the application. ```php ->plugin( SpatieLaravelTranslatablePlugin::make() ->defaultLocales(['en', 'es']) // Configure here ) ``` -------------------------------- ### List Records Usage with Translatable Trait Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Example of integrating the Translatable trait into a Filament ListRecords page to enable locale switching for table display and searching. ```php use Filament\Actions; use Filament\Resources\Pages\ListRecords; class ListBlogPosts extends ListRecords { use Translatable; protected function getHeaderActions(): array { return [ Actions\LocaleSwitcher::make(), ]; } } ``` -------------------------------- ### Database-Agnostic JSON Search Constraints Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/architecture.md Provides example SQL queries for searching within JSON translation columns, adapting syntax for different database systems like PostgreSQL and MySQL/SQLite. ```sql // PostgreSQL WHERE translations->>'es' LIKE '%search%' // MySQL/SQLite WHERE json_extract(translations, "$.es") LIKE '%search%' ``` -------------------------------- ### Configure Spatie Laravel Translatable Plugin Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/configuration.md Example of configuring the Spatie Laravel Translatable plugin within a Filament PanelProvider. This includes setting default locales and a custom locale label formatter. ```php // PanelProvider.php use Filament\Panel; use Filament\PanelProvider; use Filament\SpatieLaravelTranslatablePlugin; class AdminPanelProvider extends PanelProvider { public function panel(Panel $panel): Panel { return $panel ->default() ->id('admin') ->path('admin') // ... other configuration ->plugin( SpatieLaravelTranslatablePlugin::make() ->defaultLocales(['en', 'es', 'fr', 'de', 'it', 'pt']) ->getLocaleLabelUsing(function (string $locale) { return match ($locale) { 'en' => '🇬🇧 English', 'es' => '🇪🇸 Español', 'fr' => '🇫🇷 Français', 'de' => '🇩🇪 Deutsch', 'it' => '🇮🇹 Italiano', 'pt' => '🇵🇹 Português', default => null, }; }) ); } } ``` -------------------------------- ### Non-Reactive Relation Manager Setup Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/RelationManagerTranslatable.md Configure a relation manager to maintain its own independent locale state by not using the `#[Reactive]` attribute and including a `LocaleSwitcher`. This allows users to browse translations different from the parent resource page. ```php class BlogPostsRelationManager extends RelationManager { use Translatable; // $activeLocale is not reactive public ?string $activeLocale = null; public function table(Table $table): Table { return $table ->headerActions([ Tables\Actions\LocaleSwitcher::make(), ]); } } ``` -------------------------------- ### Model Setup with HasTranslations Trait Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/README.md Ensure your Eloquent models use Spatie's `HasTranslations` trait and declare the translatable attributes in the `$translatable` array. This enables the model to handle multi-language content for specified fields. ```php use Spatie\Translatable\HasTranslations; class BlogPost extends Model { use HasTranslations; public array $translatable = ['title', 'content', 'slug']; } ``` -------------------------------- ### Configure Plugin with Default Locales and Custom Labels Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/README.md Configure the plugin in your Filament panel provider to set default locales and define custom labels for each locale. This setup ensures the plugin knows which languages to support and how to display them. ```php use Filament\SpatieLaravelTranslatablePlugin; ->plugin( SpatieLaravelTranslatablePlugin::make() ->defaultLocales(['en', 'es', 'fr', 'de']) ->getLocaleLabelUsing(fn($locale) => match($locale) { 'en' => 'English', 'es' => 'Español', 'fr' => 'Français', 'de' => 'Deutsch', default => null, }) ) ``` -------------------------------- ### Content Metrics Statistics Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/MANIFEST.md Summarizes the overall content metrics of the documentation, including line counts, word counts, and the approximate number of code examples, classes, traits, methods, and configuration options. ```text Total lines: ~5,000 lines Total words: ~25,000 words Code examples: 100+ examples Classes documented: 4 main classes Traits documented: 10+ traits Methods documented: 50+ methods Configuration keys: 10+ options ``` -------------------------------- ### File Dependencies Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/00_START_HERE.md Illustrates the relationship between the main documentation file (START_HERE.md) and other referenced files within the project. ```text START_HERE.md (this file) ├─ README.md (overview) ├─ INDEX.md (navigation) ├─ IMPLEMENTATION_GUIDE.md (setup) ├─ configuration.md (options) ├─ architecture.md (design) ├─ EXPORTS_REFERENCE.md (API listing) └─ api-reference/ ├─ SpatieLaravelTranslatablePlugin.md ├─ LocaleSwitcher.md ├─ ResourceTranslatable.md ├─ ResourcePageTranslatable.md ├─ RelationManagerTranslatable.md └─ SpatieLaravelTranslatableContentDriver.md ``` -------------------------------- ### Filament\SpatieLaravelTranslatablePluginServiceProvider Boot Method Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Shows the boot method for the Filament\SpatieLaravelTranslatablePluginServiceProvider, responsible for bootstrapping the plugin's services. ```php public function boot(): void ``` -------------------------------- ### Get Active Actions Locale Method Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Returns the active locale for actions. Less restrictive than getActiveFormsLocale() as it does not validate against available locales. ```php public function getActiveActionsLocale(): ?string ``` -------------------------------- ### Import Main Plugin Component Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Import the main plugin class for initialization. ```php use Filament\SpatieLaravelTranslatablePlugin; ``` -------------------------------- ### Edit Record Usage with Translatable Trait Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Example of integrating the Translatable trait into a Filament EditRecord page to enable locale switching. ```php use Filament\Actions; use Filament\Resources\Pages\EditRecord; class EditBlogPost extends EditRecord { use Translatable; protected function getHeaderActions(): array { return [ Actions\LocaleSwitcher::make(), ]; } } ``` -------------------------------- ### Instantiate Plugin with make() Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/SpatieLaravelTranslatablePlugin.md Use the factory method to instantiate or retrieve the plugin from the Laravel service container. ```php use Filament\SpatieLaravelTranslatablePlugin; $plugin = SpatieLaravelTranslatablePlugin::make(); ``` -------------------------------- ### Get Default Translatable Locale Method Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/RelationManagerTranslatable.md Returns the default locale, which is the first locale in the list returned by getTranslatableLocales(). Used when initializing the active locale. ```php public function getDefaultTranslatableLocale(): string { // ... implementation details ... } ``` -------------------------------- ### SpatieLaravelTranslatablePlugin Constructor and Registration Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Shows the constructor and static factory method for the plugin, along with its registration and boot methods. ```php final public function __construct() {} public static function make(): static public function register(Panel $panel): void public function boot(Panel $panel): void ``` -------------------------------- ### Manually Using Spatie Laravel Translatable Content Driver Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/SpatieLaravelTranslatableContentDriver.md Demonstrates how to manually instantiate and use the Spatie Laravel Translatable Content Driver to manage translations for Eloquent models. This includes creating, updating, and retrieving translated records, as well as applying search constraints. ```php use Filament\SpatieLaravelTranslatableContentDriver; $driver = new SpatieLaravelTranslatableContentDriver('es'); // Create new record with Spanish translations $post = $driver->makeRecord(BlogPost::class, [ 'title' => 'Mi Artículo', 'content' => 'Contenido del artículo', 'author_id' => 1, ]); $post->save(); // Update existing record $post = $driver->updateRecord($post, [ 'title' => 'Título Actualizado', ]); // Get form data from record $data = $driver->getRecordAttributesToArray($post); // Search translations $query = BlogPost::query(); $query = $driver->applySearchConstraintToQuery( $query, 'translations', 'Artículo', 'where' ); ``` -------------------------------- ### Customize Default Action Labels Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/configuration.md Edit the default translation file to customize labels like 'Locale' for the LocaleSwitcher action. This example changes 'Locale' to 'Language'. ```php // resources/lang/vendor/filament-spatie-laravel-translatable-plugin-translations/en/actions.php return [ 'active_locale' => [ 'label' => 'Locale', ], ]; ``` ```php return [ 'active_locale' => [ 'label' => 'Language', // Changed from 'Locale' ], ]; ``` -------------------------------- ### Import Content Driver Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Import the content driver for integrating translatable content. ```php use Filament\SpatieLaravelTranslatableContentDriver; ``` -------------------------------- ### Get Available Locales for Create Record Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md The getTranslatableLocales method returns an array of available locale codes for the page. It delegates this responsibility to the resource's own getTranslatableLocales() method. ```php public function getTranslatableLocales(): array ``` -------------------------------- ### Get Default Translatable Locale Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourceTranslatable.md Retrieves the default locale for translations, which is the first locale in the configured list. Use this to determine the primary language for new records or page loads. ```php use Filament\Resources\Concerns\Translatable; class BlogPostResource extends Resource { use Translatable; public static function getTranslatableLocales(): array { return ['en', 'es', 'fr']; } } $locale = BlogPostResource::getDefaultTranslatableLocale(); // Returns 'en' ``` -------------------------------- ### Publish Translation Files Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/README.md Use this Artisan command to publish the package's language files, allowing you to translate the plugin's strings. ```bash php artisan vendor:publish --tag=filament-spatie-laravel-translatable-plugin-translations ``` -------------------------------- ### Plugin Configuration Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/README.md Configure global locales and custom locale labels for the plugin. ```php SpatieLaravelTranslatablePlugin::make() ->defaultLocales(array $locales) // Global locales ->getLocaleLabelUsing(Closure $callback) // Custom labels ``` -------------------------------- ### Add Plugin to Panel Configuration Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/README.md Include the plugin in your panel configuration using the `plugin()` method. ```php use Filament\SpatieLaravelTranslatablePlugin; public function panel(Panel $panel): Panel { return $panel // ... ->plugin(SpatieLaravelTranslatablePlugin::make()); } ``` -------------------------------- ### Get Locale Label Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/SpatieLaravelTranslatablePlugin.md Retrieves the display label for a locale code. It can use a custom callback or fall back to a default method. The `displayLocale` parameter influences the language of the returned label. ```php public function getLocaleLabel(string $locale, ?string $displayLocale = null): ?string ``` ```php $plugin = SpatieLaravelTranslatablePlugin::make(); // Without custom callback $label = $plugin->getLocaleLabel('es'); // Returns "Spanish" in app locale $label = $plugin->getLocaleLabel('es', 'es'); // Returns "Español" // With custom callback $plugin->getLocaleLabelUsing(fn($locale) => match($locale) { 'en' => '🇬🇧 English', 'es' => '🇪🇸 Spanish', default => null, }); $label = $plugin->getLocaleLabel('es'); // Returns "🇪🇸 Spanish" ``` -------------------------------- ### Create Flow Data Handling Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/architecture.md Outlines the data flow during the record creation process, including locale initialization, form population, and saving translations. ```php CreateRecord Page ├─ mountTranslatable() │ └─ $activeLocale = getDefaultTranslatableLocale() │ ├─ Form display │ └─ User enters data in active locale │ ├─ updatedActiveLocale() │ ├─ Save current form to $otherLocaleData │ └─ Load different locale form │ ├─ User saves └─ handleRecordCreation() ├─ Create model ├─ Fill non-translatable attributes ├─ setTranslation(key, activeLocale, value) for each ├─ For each locale in $otherLocaleData │ ├─ Validate │ └─ setTranslation(key, locale, value) └─ $record->save() ``` -------------------------------- ### Get Translatable Attributes from Model Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourceTranslatable.md Retrieves the translatable attributes defined in the resource's model. The model must use Spatie's HasTranslations trait and specify a `$translatable` property. ```php // Model definition class BlogPost extends Model { use HasTranslations; public array $translatable = ['title', 'content', 'slug']; } // In resource class BlogPostResource extends Resource { use Translatable; public static function form(Form $form): Form { $attrs = static::getTranslatableAttributes(); // ['title', 'content', 'slug'] return $form ->schema([ Forms\Components\TextInput::make('title') ->required(), Forms\Components\Textarea::make('content'), Forms\Components\TextInput::make('slug'), ]); } } ``` -------------------------------- ### Locale Switcher Action Example Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/README.md The `LocaleSwitcher` action generates a dropdown UI element for users to select their desired locale. This action is typically added to the header actions of resource pages. ```php Actions\LocaleSwitcher::make() // Renders as dropdown with options like: // 🇬🇧 English // 🇪🇸 Español // 🇫🇷 Français ``` -------------------------------- ### Publish Translations Command Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/LocaleSwitcher.md Command to publish language files for customizing the locale switcher label. ```bash php artisan vendor:publish --tag=filament-spatie-laravel-translatable-plugin-translations ``` -------------------------------- ### Get Active Table Locale (List Records) Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Returns the currently active locale for table column searching and display. This is used by the translatable content driver to search data in the correct locale. ```php public function getActiveTableLocale(): ?string ``` -------------------------------- ### Register and Configure Plugin in Filament Panel Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/SpatieLaravelTranslatablePlugin.md Demonstrates how to register the Spatie Laravel Translatable Plugin within a Filament panel's `panel()` method. It shows setting default locales and a custom locale label callback. ```php use Filament\SpatieLaravelTranslatablePlugin; use Filament\Panel; public function panel(Panel $panel): Panel { return $panel // ... other configuration ->plugin( SpatieLaravelTranslatablePlugin::make() ->defaultLocales(['en', 'es', 'fr', 'de']) ->getLocaleLabelUsing(function (string $locale) { return match ($locale) { 'en' => 'English', 'es' => 'Español', 'fr' => 'Français', 'de' => 'Deutsch', default => null, }; }) ); } ``` -------------------------------- ### Livewire Lifecycle Hooks for Translation Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/README.md Utilize Livewire lifecycle hooks for initializing locale and managing locale changes. ```php public function mountTranslatable(): void // Initialize locale public function updatingActiveLocale(): void // Before locale change public function updatedActiveLocale(): void // After locale change ``` -------------------------------- ### Translatable Resource Methods Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/INDEX.md These static methods provide information about translatable locales, the default translatable locale, and translatable attributes for resources. ```php static::getTranslatableLocales() static::getDefaultTranslatableLocale() static::getTranslatableAttributes() ``` -------------------------------- ### Create Translatable Filament Resource Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/IMPLEMENTATION_GUIDE.md Create a Filament resource and use the `Translatable` trait. Define the form schema with translatable fields. ```php // app/Filament/Resources/BlogPostResource.php use Filament\Forms; use Filament\Resources\Resource; use Filament\Resources\Concerns\Translatable; use Filament\Tables; use App\Models\BlogPost; class BlogPostResource extends Resource { use Translatable; protected static ?string $model = BlogPost::class; protected static ?string $navigationIcon = 'heroicon-o-document-text'; public static function form(Forms\Form $form): Forms\Form { return $form ->schema([ Forms\Components\TextInput::make('title') ->required() ->maxLength(255), Forms\Components\Textarea::make('content') ->required(), Forms\Components\TextInput::make('slug') ->required() ->unique(ignoreRecord: true), Forms\Components\Select::make('author_id') ->relationship('author', 'name') ->required(), Forms\Components\DateTimePicker::make('published_at'), ]); } public static function table(Tables\Table $table): Tables\Table { return $table ->columns([ Tables\Columns\TextColumn::make('title') ->searchable() ->sortable(), Tables\Columns\TextColumn::make('author.name') ->searchable() ->sortable(), Tables\Columns\TextColumn::make('published_at') ->dateTime() ->sortable(), ]) ->filters([ Tables\Filters\TrashedFilter::make(), ]) ->actions([ Tables\Actions\EditAction::make(), Tables\Actions\DeleteAction::make(), ]); } } ``` -------------------------------- ### File Count and Size Statistics Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/MANIFEST.md Displays the total number of files and their aggregated size for both root directory files and API reference files. ```text Root files: 8 files (99 KB) API reference files: 6 files (61 KB) Total: 13 files (160 KB) ``` -------------------------------- ### Configure Spatie Laravel Translatable Plugin Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/INDEX.md Use the make factory method to instantiate the plugin and configure default locales. You can also define a custom callback for generating locale labels. ```php SpatieLaravelTranslatablePlugin::make() ->defaultLocales(['en', 'es']) ->getLocaleLabelUsing(fn($locale) => ...) ->getDefaultLocales() ->getLocaleLabel('en', 'es') ``` -------------------------------- ### Get Active Table Locale Method Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/RelationManagerTranslatable.md Returns the active locale for table column searching and display. Used by Filament's translatable content driver to determine which locale's data to display and search. ```php public function getActiveTableLocale(): ?string { // ... implementation details ... } ``` -------------------------------- ### Custom Locale Labels (Simple Match) Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/configuration.md Provide a custom callback to define human-readable labels for locale codes using a simple `match` statement. This allows for specific naming conventions. ```php ->plugin( SpatieLaravelTranslatablePlugin::make() ->defaultLocales(['en', 'es', 'fr', 'de']) ->getLocaleLabelUsing(function (string $locale) { return match ($locale) { 'en' => 'English', 'es' => 'Español', 'fr' => 'Français', 'de' => 'Deutsch', default => null, }; }) ) ``` -------------------------------- ### HasActiveLocaleSwitcher Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Base trait providing locale management properties and methods for Filament resource pages. It tracks the active locale and provides methods to get the active locale for forms and actions, as well as the translatable content driver. ```APIDOC ## Trait: HasActiveLocaleSwitcher ### Description Provides locale management properties and methods for Filament resource pages. It tracks the currently active locale and offers utilities for retrieving locale-specific data for forms and actions. ### Location `src/Resources/Concerns/HasActiveLocaleSwitcher.php:8` ### Properties - **$activeLocale** (string | null) - Tracks the currently active locale for the page. Automatically managed when using `LocaleSwitcher` action. ### Methods #### `getActiveFormsLocale()` - **Returns:** `string | null` - The active locale if it's in the list of available locales, otherwise `null`. - **Description:** Returns the currently active locale for form components. Used internally by Filament to determine which translation to display in form fields. Returns `null` if the active locale is not in the configured locales, preventing display of invalid locale data. #### `getActiveActionsLocale()` - **Returns:** `string | null` - The currently active locale. - **Description:** Returns the active locale for actions. Less restrictive than `getActiveFormsLocale()` as it does not validate against available locales. #### `getFilamentTranslatableContentDriver()` - **Returns:** `string | null` - The class name `SpatieLaravelTranslatableContentDriver::class`. - **Description:** Returns the translatable content driver class used to handle form data translation. Filament uses this to transform form data when saving records with multiple locale translations. ``` -------------------------------- ### Get Translatable Locales Method Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/RelationManagerTranslatable.md Returns the locales available in this relation manager. Uses the globally configured plugin locales. Unlike resource pages, relation managers do not support per-relation-manager locale customization in the base implementation. ```php public function getTranslatableLocales(): array { // ... implementation details ... } ``` ```php $locales = $this->getTranslatableLocales(); // ['en', 'es', 'fr'] ``` -------------------------------- ### Get Filament Translatable Content Driver Method Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Returns the translatable content driver class used to handle form data translation. Filament uses this to transform form data when saving records with multiple locale translations. ```php public function getFilamentTranslatableContentDriver(): ?string ``` -------------------------------- ### Get Record Attributes as Array with Active Locale Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/SpatieLaravelTranslatableContentDriver.md Converts a model record into an array, ensuring that translatable attributes are replaced with their values from the active locale. Non-translatable attributes are included as-is. This is useful for populating forms with existing data. ```php public function getRecordAttributesToArray(Model $record): array { // ... implementation details ... } $driver = new SpatieLaravelTranslatableContentDriver('es'); $record = BlogPost::find(1); // Record has: title (es: "Título"), content (es: "Contenido"), author_id: 5 $array = $driver->getRecordAttributesToArray($record); // Returns: // [ // 'title' => 'Título', // 'content' => 'Contenido', // 'author_id' => 5, // ] ``` -------------------------------- ### Filament SpatieLaravelTranslatablePlugin Methods Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Lists the static and public methods available on the Filament\SpatieLaravelTranslatablePlugin class. These methods are used for plugin initialization and configuration. ```php public static function make(): static public function getId(): string public function register(Panel $panel): void public function boot(Panel $panel): void public function defaultLocales(?array $defaultLocales = null): static public function getDefaultLocales(): array public function getLocaleLabelUsing(?Closure $callback): static public function getLocaleLabel(string $locale, ?string $displayLocale = null): ?string ``` -------------------------------- ### Get Record Method for Translatable Data Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Overrides the page's getRecord() method to set the model's locale to the active locale before returning. This ensures the model will return translations for the active locale when accessed. If no activeLocale is set, returns the record unmodified. ```php public function getRecord(): Model ``` -------------------------------- ### Get Default Translatable Locale Method Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Determines the default locale to use when filling the form. Checks which locales the record has translations for, and returns the resource's default locale if available; otherwise returns the first matching locale between record translations and available locales. ```php protected function getDefaultTranslatableLocale(): string ``` -------------------------------- ### Get Active Forms Locale Method Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Returns the currently active locale for form components. Used internally by Filament to determine which translation to display in form fields. Returns null if the active locale is not in the configured locales, preventing display of invalid locale data. ```php public function getActiveFormsLocale(): ?string ``` -------------------------------- ### Mount Translatable Hook Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/RelationManagerTranslatable.md Livewire mount hook that initializes the active locale. Sets $activeLocale to the default translatable locale if not already set or if the current value is not in the available locales. ```php public function mountTranslatable(): void { // ... implementation details ... } ``` -------------------------------- ### Trait Composition for Pages Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Illustrates how page translatable traits compose to provide locale switching and form/record handling capabilities. ```plaintext PageSpecificTrait └─ HasActiveLocaleSwitcher ├─ $activeLocale property ├─ getActiveFormsLocale() ├─ getActiveActionsLocale() └─ getFilamentTranslatableContentDriver() EditRecordTrait ├─ HasActiveLocaleSwitcher ├─ HasTranslatableFormWithExistingRecordData │ └─ $otherLocaleData property │ └─ fillForm() └─ HasTranslatableRecord └─ getRecord() ``` -------------------------------- ### Form Component Integration Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Shows how standard Filament form components can be used with the plugin, as translation is handled at the page level. ```php Forms\Components\TextInput::make('title') Forms\Components\Textarea::make('content') Forms\Components\Select::make('category_id') ``` -------------------------------- ### Import Resource Trait Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Import the Translatable trait to enable translation features on Filament Resources. ```php use Filament\Resources\Concerns\Translatable; ``` -------------------------------- ### Add Locale Switcher to Header Actions Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/IMPLEMENTATION_GUIDE.md Demonstrates how to add the `LocaleSwitcher` action to the header of a Filament page to enable language selection. ```php protected function getHeaderActions(): array { return [ Actions\LocaleSwitcher::make(), // Add this ]; } ``` -------------------------------- ### Create Translatable Relation Manager Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/IMPLEMENTATION_GUIDE.md Implement a translatable relation manager for related translatable models, including a locale switcher in its table actions. ```php // app/Filament/Resources/BlogPostResource/RelationManagers/CommentsRelationManager.php use Filament\Resources\RelationManagers\RelationManager; use Filament\Resources\RelationManagers\Concerns\Translatable; use Filament\Tables; use Filament\Tables\Table; use Livewire\Attributes\Reactive; class CommentsRelationManager extends RelationManager { use Translatable; protected static string $relationship = 'comments'; public function table(Table $table): Table { return $table ->columns([ Tables\Columns\TextColumn::make('author') ->searchable(), Tables\Columns\TextColumn::make('content') ->limit(50), Tables\Columns\TextColumn::make('created_at') ->dateTime(), ]) ->headerActions([ Tables\Actions\CreateAction::make(), Tables\Actions\LocaleSwitcher::make(), ]) ->actions([ Tables\Actions\EditAction::make(), Tables\Actions\DeleteAction::make(), ]); } } ``` -------------------------------- ### Access Plugin via Service Container Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/SpatieLaravelTranslatablePlugin.md Shows how to retrieve the Spatie Laravel Translatable Plugin instance from the service container using the `filament()` helper function and access its default locales. ```php $plugin = filament('spatie-laravel-translatable'); $locales = $plugin->getDefaultLocales(); ``` -------------------------------- ### makeRecord Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/SpatieLaravelTranslatableContentDriver.md Creates a new, unsaved model instance populated with provided data, correctly handling both translatable and non-translatable attributes for the active locale. ```APIDOC ## makeRecord(string $model, array $data) ### Description Creates a new model instance with the provided data, separating translatable and non-translatable attributes. Non-translatable attributes are filled directly; translatable attributes are set via `setTranslation()` for the active locale. The model is not saved. ### Method ```php public function makeRecord(string $model, array $data): Model ``` ### Parameters #### Path Parameters - **model** (string) - Required - Model class name (FQCN) - **data** (array) - Required - Form data containing both translatable and non-translatable fields ### Returns - **Model** — New unsaved model instance with translations set. ### Flow: 1. Creates new model instance 2. Sets locale to active locale (if model supports it) 3. Extracts non-translatable attributes and fills the model 4. For each translatable attribute, calls `setTranslation(key, activeLocale, value)` ### Example: ```php $driver = new SpatieLaravelTranslatableContentDriver('en'); $record = $driver->makeRecord( BlogPost::class, [ 'title' => 'My Blog Post', 'content' => 'Post content..', 'author_id' => 1, 'published' => true, ] ); // Record has translations set but is not saved // $record->getTranslation('title', 'en') === 'My Blog Post' ``` ``` -------------------------------- ### SpatieLaravelTranslatablePlugin::make() Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/SpatieLaravelTranslatablePlugin.md Factory method to instantiate or retrieve the plugin from the Laravel service container. This is the recommended way to create an instance of the plugin. ```APIDOC ## SpatieLaravelTranslatablePlugin::make() ### Description Factory method to instantiate or retrieve the plugin from the Laravel service container. ### Method `public static function make(): static` ### Returns `static` — New instance of the plugin retrieved from the service container. ### Example ```php use Filament\SpatieLaravelTranslatablePlugin; $plugin = SpatieLaravelTranslatablePlugin::make(); ``` ``` -------------------------------- ### Initialize Translatable Trait in Relation Manager Mount Hook Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/RelationManagerTranslatable.md Ensure the `Translatable` trait is properly initialized by calling `$this->mountTranslatable()` within your relation manager's `mount()` method. This is crucial for locale management during the Livewire component's mounting phase. ```php class BlogPostsRelationManager extends RelationManager { use Translatable; public function mount(): void { parent::mount(); $this->mountTranslatable(); // Initialize locale } } ``` -------------------------------- ### ListRecords Translatable Methods Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/api-reference/ResourcePageTranslatable.md Methods for enabling locale switching and display on the List Records page. ```APIDOC ## `mountTranslatable()` ### Description Initializes the active locale for the list page, typically setting it to the resource's default locale. ### Method GET ### Endpoint N/A (Method within a class) ### Returns - `void` ``` ```APIDOC ## `getTranslatableLocales()` ### Description Retrieves an array of locale codes that are available for translation within the list resource. ### Method GET ### Endpoint N/A (Method within a class) ### Returns - `array` - An array of locale codes. ``` ```APIDOC ## `getActiveTableLocale()` ### Description Returns the currently active locale being used for table column searching and display. This is crucial for the translatable content driver to correctly query data in the specified locale. ### Method GET ### Endpoint N/A (Method within a class) ### Returns - `string | null` - The active locale code, or null if none is set. ``` -------------------------------- ### Enable Translation on Resource Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Use the Translatable concern within a Filament Resource to enable translation capabilities. ```php use Translatable; ``` -------------------------------- ### Update Resource Routes for Translatable Pages Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/IMPLEMENTATION_GUIDE.md Configure the `getPages()` method in your resource to correctly route to the translatable pages. ```php // app/Filament/Resources/BlogPostResource.php public static function getPages(): array { return [ 'index' => Pages\ListBlogPosts::route('/'), 'create' => Pages\CreateBlogPost::route('/create'), 'edit' => Pages\EditBlogPost::route('/{record}/edit'), 'view' => Pages\ViewBlogPost::route('/{record}'), ]; } ``` -------------------------------- ### Import Locale Switcher Actions Source: https://github.com/filamentphp/spatie-laravel-translatable-plugin/blob/3.x/_autodocs/EXPORTS_REFERENCE.md Import the LocaleSwitcher action for use in pages and tables. ```php use Filament\Actions\LocaleSwitcher; ``` ```php use Filament\Tables\Actions\LocaleSwitcher; ```