### Install Spatie Laravel Translatable Package via Composer Source: https://spatie.be/docs/laravel-translatable/v6/introduction/installation-setup This Composer command installs the `spatie/laravel-translatable` package into your Laravel project. It's the first step to enable multi-language support for your models. ```Bash composer require spatie/laravel-translatable ``` -------------------------------- ### Set Multiple Translations (Laravel) Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Provides examples for setting translations for multiple languages. This can be achieved by assigning an associative array of translations to the attribute or by using the `setTranslations` method. The changes must be saved to persist them to the database. ```PHP $translations = ['en' => 'hello', 'es' => 'hola']; $newItem->name = $translations; // alternatively, use the `setTranslations` method $newsItem->setTranslations('name', $translations); $newItem->save(); ``` -------------------------------- ### Configure Laravel Model for Translations Source: https://spatie.be/docs/laravel-translatable/v6/introduction/installation-setup This PHP code snippet demonstrates how to make a Laravel Eloquent model translatable. It involves adding the `Spatie\Translatable\HasTranslations` trait and defining a public `$translatable` array property with the names of attributes that should be translatable. Ensure these attributes are set to the `json` datatype in your database. ```PHP use Illuminate\Database\Eloquent\Model; use Spatie\Translatable\HasTranslations; class NewsItem extends Model { use HasTranslations; public array $translatable = ['name']; } ``` -------------------------------- ### Get All Translations for a Model Attribute Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Demonstrates how to retrieve all translations associated with a model attribute using the `getTranslations()` method or the `translations` accessor. It shows how the method returns an array of translations keyed by locale. ```PHP $newsItem->getTranslations(); ``` ```PHP $yourModel->translations ``` ```PHP $newsItem->getTranslations('name'); // returns ['en' => 'Name in English', 'nl' => 'Naam in het Nederlands'] ``` -------------------------------- ### Set and Get Specific Translations by Locale Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Illustrates how to set multiple translations for an attribute and then retrieve specific translations by providing an array of allowed locales to the `getTranslations()` method. This allows for filtering the returned translations. ```PHP $translations = [ 'en' => 'Hello', 'fr' => 'Bonjour', 'de' => 'Hallo' ]; $newsItem->setTranslations('hello', $translations); $newsItem->getTranslations('hello', ['en', 'fr']); // returns ['en' => 'Hello', 'fr' => 'Bonjour'] ``` -------------------------------- ### Set Translations on Model Creation (Laravel) Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Shows how to set translations for multiple locales directly when creating a new model instance. An associative array, where keys are locales and values are translations, is passed to the attribute during model creation. ```PHP NewsItem::create([ 'name' => [ 'en' => 'Name in English', 'nl' => 'Naam in het Nederlands' ], ]); ``` -------------------------------- ### getTranslations Method API Signature Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Defines the signature for the `getTranslations` method, which allows retrieving translations for a specific attribute, optionally filtered by an array of allowed locales. It returns an array of translations. ```APIDOC public function getTranslations(string $attributeName, array $allowedLocales): array ``` -------------------------------- ### Example: Replacing Translations in Laravel-translatable Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/replacing-translations Demonstrates how to use the `replaceTranslations` method to update all translations for a given key on a translatable model. It shows initial setting, retrieving, and then replacing translations with a new set. ```PHP $translations = ['en' => 'hello', 'es' => 'hola']; $newsItem->setTranslations('hello', $translations); $newsItem->getTranslations(); // ['en' => 'hello', 'es' => 'hola'] $newTranslations = ['en' => 'hello']; $newsItem->replaceTranslations('hello', $newTranslations); $newsItem->getTranslations(); // ['en' => 'hello'] ``` -------------------------------- ### Get Locales Associated with a Model Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Shows how to retrieve all locales for which a model has translations. After setting and saving translations, the `locales()` method can be used to get an array of the available locales. ```PHP $translations = ['en' => 'hello', 'es' => 'hola']; $newItem->name = $translations; $newItem->save(); $newItem->locales(); // returns ['en', 'es'] ``` -------------------------------- ### Set and Get Translations for Eloquent Models in Laravel Source: https://spatie.be/docs/laravel-translatable/v6/introduction/introduction This PHP code snippet demonstrates the basic usage of the `laravel-translatable` trait. It shows how to instantiate an Eloquent model, set translations for a specific attribute ('name') in multiple languages (English and Dutch), save the model, and then retrieve the translated attribute based on the current application locale or by explicitly specifying a locale. ```PHP $newsItem = new NewsItem(); // This is an Eloquent model $newsItem ->setTranslation('name', 'en', 'Name in English') ->setTranslation('name', 'nl', 'Naam in het Nederlands') ->save(); $newsItem->name; // Returns 'Name in English' given that the current app locale is 'en' $newsItem->getTranslation('name', 'nl'); // returns 'Naam in het Nederlands' app()->setLocale('nl'); $newsItem->name; // Returns 'Naam in het Nederlands' ``` -------------------------------- ### Integrate Translations Helper in Laravel Factory Definition Source: https://spatie.be/docs/laravel-translatable/v6/introduction/advanced-usage/usage-with-factories Provides a complete example of how to integrate the `translations` helper into a Laravel Eloquent factory's `definition` method. This snippet shows how to assign a translatable attribute, such as 'bio', using the helper. ```PHP class UserFactory extends \Illuminate\Database\Eloquent\Factories\Factory { public function definition(): array { return [ 'bio' => $this->translations('en', 'english'), ]; } } ``` -------------------------------- ### Save Translation After Assignment (Laravel) Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Illustrates how to persist a translation to the database after assigning it to a translatable attribute by calling the `save()` method on the model. This step is crucial for saving changes. ```PHP $newsItem->name = 'New translation' $newsItem->save(); ``` -------------------------------- ### Get Translation for Current Locale (Laravel) Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Demonstrates how to retrieve the translation for a translatable attribute for the current application locale by simply accessing the model property. This is the easiest way to get the current locale's translation. ```PHP $newsItem->name; ``` -------------------------------- ### PHP: Example Usage of `forgetAllTranslations` Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/removing-translations An example demonstrating how to call the `forgetAllTranslations` method on a `$newsItem` model instance to remove all translations associated with the 'nl' (Dutch) locale. ```PHP $newsItem->forgetAllTranslations('nl'); ``` -------------------------------- ### setTranslation Method Signature (Laravel) Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Documents the `setTranslation` method signature. This method allows setting a specific translation for a given attribute and locale. Parameters include the attribute name (string), locale (string), and the translation value (string). ```APIDOC public function setTranslation(string $attributeName, string $locale, string $value) ``` -------------------------------- ### Set Translation for Current Locale (Laravel) Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Demonstrates setting a translation for a translatable attribute by directly assigning a string value to the model property. This translation will be applied to the current application locale and requires a subsequent `save()` call to persist. ```PHP $newsItem->name = 'New translation'; ``` -------------------------------- ### getTranslation Method Signature (Laravel) Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/getting-and-settings-translations Documents the `getTranslation` method signature. This method retrieves a specific translation for a given attribute and locale, with an optional parameter to use a fallback locale if the requested translation is not found. It returns the translation as a string. ```APIDOC public function getTranslation(string $attributeName, string $locale, bool $useFallbackLocale = true) : string ``` -------------------------------- ### PHP: Example Usage of `forgetTranslation` Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/removing-translations An example demonstrating how to call the `forgetTranslation` method on a `$newsItem` model instance to remove the 'name' translation for the 'nl' (Dutch) locale. ```PHP $newsItem->forgetTranslation('name', 'nl'); ``` -------------------------------- ### Customize Laravel Translatable Fallback for Remote Translation Service Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/handling-missing-translations This PHP example shows how to configure a fallback callback for Spatie\Translatable that returns a string from a remote translation service. When a translation key is missing, the callback attempts to fetch an automatic translation, providing a dynamic fallback mechanism. ```PHP use Spatie\Translatable\Facades\Translatable; use App\Service\MyRemoteTranslationService; Translatable::fallback(missingKeyCallback: function ( Model $model, string $translationKey, string $locale, string $fallbackTranslation, string $fallbackLocale ) { return MyRemoteTranslationService::getAutomaticTranslation($fallbackTranslation, $fallbackLocale, $locale); }); ``` -------------------------------- ### Set Specific Fallback Locale for Laravel Translatable Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/handling-missing-translations This example shows how to specify a particular fallback locale, such as 'fr', that differs from the application's default fallback locale defined in `config/app.php`. This allows for more granular control over translation fallbacks. ```PHP use Spatie\Translatable\Facades\Translatable; Translatable::fallback( fallbackLocale: 'fr', ); ``` -------------------------------- ### Set and Retrieve Translations for Eloquent Models in Laravel Source: https://spatie.be/docs/laravel-translatable/v6/introduction/index This PHP code snippet demonstrates the basic usage of the `laravel-translatable` package. It shows how to create an Eloquent model, set translations for a specific attribute ('name') in multiple languages (English and Dutch), save the model, and then retrieve the translations based on the current application locale or by explicitly specifying the locale. ```PHP $newsItem = new NewsItem(); // This is an Eloquent model $newsItem ->setTranslation('name', 'en', 'Name in English') ->setTranslation('name', 'nl', 'Naam in het Nederlands') ->save(); $newsItem->name; // Returns 'Name in English' given that the current app locale is 'en' $newsItem->getTranslation('name', 'nl'); // returns 'Naam in het Nederlands' app()->setLocale('nl'); $newsItem->name; // Returns 'Naam in het Nederlands' ``` -------------------------------- ### Querying Records by Locale Presence Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/querying-translations Shows how to retrieve records based on whether a translation exists for a specific locale or any of a list of locales. The `whereLocale` method checks for a single locale, while `whereLocales` checks for multiple. ```php NewsItem::whereLocale('name', 'en')->get(); // Returns all news items with a name in English NewsItem::whereLocales('name', ['en', 'nl'])->get(); // Returns all news items with a name in English or Dutch ``` -------------------------------- ### Generate Translation Arrays with Factory Helper Source: https://spatie.be/docs/laravel-translatable/v6/introduction/advanced-usage/usage-with-factories Demonstrates various ways to use the `translations` helper method within a Laravel Eloquent factory. It shows how to generate translation arrays for single or multiple locales, with single or multiple translation values. ```PHP /** @var $this \Illuminate\Database\Eloquent\Factories\Factory */ $this->translations('en', 'english') // output: ['en' => 'english'] $this->translations(['en', 'nl'], 'english') // output: ['en' => 'english', 'nl' => 'english'] $this->translations(['en', 'nl'], ['english', 'dutch']) // output: ['en' => 'english', 'nl' => 'dutch'] ``` -------------------------------- ### Use Translations Helper Statically Outside Factory Source: https://spatie.be/docs/laravel-translatable/v6/introduction/advanced-usage/usage-with-factories Illustrates how the `translations` helper method can be invoked statically on the `Factory` class, allowing its use outside of a typical factory context to generate translation arrays. ```PHP \Illuminate\Database\Eloquent\Factories\Factory::translations('en', 'english'); // output: ['en' => 'english'] ``` -------------------------------- ### Configure Global Translation Fallback in Laravel Translatable Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/handling-missing-translations This snippet demonstrates how to set up the global fallback functionality for translations using the `Spatie\Translatable\Facades\Translatable` facade. This configuration is typically placed within a service provider to ensure it's applied application-wide. ```PHP use Spatie\Translatable\Facades\Translatable; Translatable::fallback( ... ); ``` -------------------------------- ### Customize Laravel Translatable Fallback for Logging Missing Keys Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/handling-missing-translations This PHP snippet demonstrates how to register a custom callback function with Spatie\Translatable to handle missing translation keys. The callback logs a warning with details about the missing key, locale, and model information, allowing developers to monitor and address untranslated content. ```PHP use Spatie\Translatable\Facades\Translatable; use Illuminate\Support\Facades\Log; Translatable::fallback(missingKeyCallback: function ( Model $model, string $translationKey, string $locale, string $fallbackTranslation, string $fallbackLocale, ) { // do something (ex: logging, alerting, etc) Log::warning('Some translation key is missing from an eloquent model', [ 'key' => $translationKey, 'locale' => $locale, 'fallback_locale' => $fallbackLocale, 'fallback_translation' => $fallbackTranslation, 'model_id' => $model->id, 'model_class' => get_class($model), ]); }); ``` -------------------------------- ### Querying Records by Locale Value Containment Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/querying-translations Explains how to query records where a translation in a specific locale or multiple locales contains a given value. `whereJsonContainsLocale` targets a single locale, and `whereJsonContainsLocales` targets multiple locales for the value check. ```php // Returns all news items that has name in English with value `Name in English` NewsItem::query()->whereJsonContainsLocale('name', 'en', 'Name in English')->get(); // Returns all news items that has name in English or Dutch with value `Name in English` NewsItem::query()->whereJsonContainsLocales('name', ['en', 'nl'], 'Name in English')->get(); ``` -------------------------------- ### Querying Translations with MySQL JSON Type Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/querying-translations Demonstrates how to query translatable columns in MySQL 5.7 or above by directly accessing the locale key within the JSON data type. This method is concise and efficient for specific locale lookups. ```php NewsItem::where('name->en', 'Name in English')->get(); ``` -------------------------------- ### Define TranslationHasBeenSetEvent in Laravel Translatable Source: https://spatie.be/docs/laravel-translatable/v6/introduction/advanced-usage/available-events This PHP class defines the `TranslationHasBeenSetEvent` which is fired right after a translation is set using the `setTranslation` method. It provides access to the model, the translation key, the locale, the old value, and the new value of the translation. ```PHP namespace Spatie\Translatable\Events; class TranslationHasBeenSetEvent { public function __construct( public mixed $model, public string $key, public string $locale, public mixed $oldValue, public mixed $newValue, ) { // } } ``` -------------------------------- ### Enable Fallback to Any Available Translation in Laravel Translatable Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/handling-missing-translations This snippet demonstrates how to configure the system to return any available translation if neither the preferred locale nor the explicitly defined fallback locale is found. This ensures that some content is always displayed, even if not in the desired language. ```PHP use Spatie\Translatable\Facades\Translatable; Translatable::fallback( fallbackAny: true, ); ``` -------------------------------- ### Querying Translations with MariaDB JSON_EXTRACT Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/querying-translations Illustrates querying translatable columns in MariaDB 10.2.3 or above using the `JSON_EXTRACT` function. This approach is necessary for MariaDB to parse JSON fields and filter by locale-specific values. ```php NewsItem::whereRaw("JSON_EXTRACT(name, '$.en') = 'Name in English'")->get(); ``` -------------------------------- ### Define Per-Model Fallback Locale in Laravel Translatable Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/handling-missing-translations This code illustrates how to implement a `getFallbackLocale()` method directly on an Eloquent model. This approach enables different models to have their own distinct fallback locales, providing flexibility for diverse content requirements. ```PHP use Illuminate\Database\Eloquent\Model; use Spatie\Translatable\HasTranslations; class NewsItem extends Model { use HasTranslations; public $fillable = ['name', 'fallback_locale']; public $translatable = ['name']; public function getFallbackLocale() : string { return $this->fallback_locale; } } ``` -------------------------------- ### Replace Translations Method Signature Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/replacing-translations Defines the `replaceTranslations` method signature, showing its parameters and return type for replacing all translations associated with a specific key on a translatable model. ```APIDOC public function replaceTranslations(string $key, array $translations) ``` -------------------------------- ### Override toArray method in custom Laravel Translatable Trait Source: https://spatie.be/docs/laravel-translatable/v6/introduction/advanced-usage/customize-the-toarray-method This PHP snippet demonstrates how to create a custom `HasTranslations` trait that extends `Spatie\Translatable\HasTranslations`. It overrides the `toArray()` method to ensure that only translatable attributes selected by the query are included, fetching their translation for the current application locale. This provides granular control over how translatable model attributes are serialized. ```PHP namespace App\Traits; use Spatie\Translatable\HasTranslations as BaseHasTranslations; trait HasTranslations { use BaseHasTranslations; public function toArray() { $attributes = $this->attributesToArray(); // attributes selected by the query // remove attributes if they are not selected $translatables = array_filter($this->getTranslatableAttributes(), function ($key) use ($attributes) { return array_key_exists($key, $attributes); }); foreach ($translatables as $field) { $attributes[$field] = $this->getTranslation($field, \App::getLocale()); } return array_merge($attributes, $this->relationsToArray()); } } ``` -------------------------------- ### Disable Laravel Translatable Fallbacks on a Per-Model Basis Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/handling-missing-translations This PHP snippet illustrates how to disable the default fallback behavior for a specific Eloquent model using the Spatie\Translatable package. By setting the $useFallbackLocale property to false within the model, translations will not fall back to the default locale if a key is missing. ```PHP use Illuminate\Database\Eloquent\Model; use Spatie\Translatable\HasTranslations; class NewsItem extends Model { use HasTranslations; public $translatable = ['name']; protected $useFallbackLocale = false; } ``` -------------------------------- ### PHP: `forgetAllTranslations` Method Signature Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/removing-translations Defines the signature of the `forgetAllTranslations` method, which allows you to remove all translations for a specific locale from a translatable model. ```PHP public function forgetAllTranslations(string $locale) ``` -------------------------------- ### PHP: `forgetTranslation` Method Signature Source: https://spatie.be/docs/laravel-translatable/v6/introduction/basic-usage/removing-translations Defines the signature of the `forgetTranslation` method, which allows you to remove a translation for a specific attribute and locale from a translatable model. ```PHP public function forgetTranslation(string $attributeName, string $locale) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.