### Install laravel-translatable via Composer
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/installation.md
This command adds the laravel-translatable package to your project's dependencies using Composer.
```bash
composer require astrotomic/laravel-translatable
```
--------------------------------
### RuleFactory Configuration Example
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/validation-rule-factory.md
Shows a configuration example for the `RuleFactory` in `config/translatable.php`. This allows customization of the key format, prefix, and suffix used by the factory.
```php
'rule_factory' => [
'format' => \Astrotomic\Translatable\Validation\RuleFactory::FORMAT_ARRAY,
'prefix' => '%',
'suffix' => '%',
]
```
--------------------------------
### Post Model with Translatable Trait
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/installation.md
Example of a Post model that uses the Translatable trait and specifies translatable attributes.
```php
use Astrotomic\Translatable\Contracts\Translatable as TranslatableContract;
use Astrotomic\Translatable\Translatable;
class Post extends Model implements TranslatableContract
{
use Translatable;
public $translatedAttributes = ['title', 'content'];
protected $fillable = ['author'];
}
```
--------------------------------
### Install Laravel Translatable
Source: https://github.com/astrotomic/laravel-translatable/blob/main/README.md
Installs the Laravel Translatable package using Composer. This is the first step to integrate multilingual support into your Laravel application.
```bash
composer require astrotomic/laravel-translatable
```
--------------------------------
### Install Laravel Translatable
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/README.md
Installs the Laravel Translatable package using Composer. This is the initial step to integrate multilingual capabilities into your Laravel application.
```bash
composer require astrotomic/laravel-translatable
```
--------------------------------
### ChildPost Model for Custom Foreign Key
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/installation.md
Example of a child model inheriting from Post, specifying a custom table and foreign key for translations.
```php
class ChildPost extends Post
{
protected $table = 'posts';
protected $translationForeignKey = 'post_id';
}
```
--------------------------------
### Publish Configuration File
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/installation.md
This Artisan command publishes the package's configuration file to your project, allowing for customization.
```bash
php artisan vendor:publish --tag=translatable
```
--------------------------------
### Create Posts Table Migration
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/installation.md
Defines the schema for the 'posts' table, including an 'author' field and timestamps.
```php
Schema::create('posts', function(Blueprint $table) {
$table->increments('id');
$table->string('author');
$table->timestamps();
});
```
--------------------------------
### PostTranslation Model
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/installation.md
Defines the PostTranslation model, which stores the translated content for posts.
```php
class PostTranslation extends Model
{
public $timestamps = false;
protected $fillable = ['title', 'content'];
}
```
--------------------------------
### MySQL Error Example
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/faq.md
Illustrates a common MySQL error encountered during migrations when foreign key constraints are involved.
```text
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'my_database.#sql-455_63'
(errno: 150) (SQL: alter table `country_translations`
add constraint country_translations_country_id_foreign foreign key (`country_id`)
references `countries` (`id`) on delete cascade)
```
--------------------------------
### ChildPostTranslation Model
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/installation.md
Defines the translation model for the ChildPost, specifying the table and fillable attributes.
```php
use Illuminate\Database\Eloquent\Model;
class ChildPostTranslation extends Model
{
protected $table = 'post_translations';
public $timestamps = false;
protected $fillable = ['title', 'content'];
}
```
--------------------------------
### Create Post Translations Table Migration
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/installation.md
Defines the schema for the 'post_translations' table, linking to the 'posts' table and storing locale-specific content.
```php
Schema::create('post_translations', function(Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->string('locale')->index();
$table->string('title');
$table->text('content');
$table->unique(['post_id', 'locale']);
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});
```
--------------------------------
### Configure Locales in config/translatable.php
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/installation.md
Defines the application's supported locales, including nested locales for regional variations.
```php
'locales' => [
'en',
'fr',
'es' => [
'MX', // mexican spanish
'CO', // colombian spanish
],
],
```
--------------------------------
### Get Translations Array
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/methods.md
Returns all translations for the model as an array, structured to be compatible with the `fill` method.
```APIDOC
getTranslationsArray()
- Returns all the translations as an array.
- The structure is the same as accepted by the `fill(array $data)` method.
- Example:
$post->getTranslationsArray();
// Returns
[
'en' => ['title' => 'My first post'],
'de' => ['title' => 'Mein erster Beitrag'],
'fr' => ['title' => 'Mon premier post'],
];
```
--------------------------------
### Get All Locales
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/locales-helper.md
Retrieves all available translation locales, including combined country-specific locales, as a flat array.
```php
$locales = \Astrotomic\Translatable\Locales::all();
// or
$locales = \Astrotomic\Translatable\Locales::toArray();
```
--------------------------------
### Get Translation or New
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/methods.md
Retrieves an instance of the translation model for a given locale, creating a new instance if one does not exist. Aliases include `getTranslationOrNew`.
```APIDOC
translateOrNew(?string $locale = null)
- Alias of: getTranslationOrNew(?string $locale = null)
- Returns an instance of the translation model for the default or given locale.
- Creates a new instance if needed.
- Examples:
$post->translateOrNew(); // returns the german translation model
$post->translateOrNew('fr'); // returns the french translation model
$post->translateOrNew('it'); // returns the new italian translation model
```
--------------------------------
### Create Role User Table Migration
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/usage/pivot-model.md
A database migration example for creating the 'role_user' pivot table. It includes an auto-incrementing 'id' as the primary key, foreign keys for user_id and role_id, and a unique constraint.
```php
Schema::create('role_user', function(Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->unique(['user_id', 'role_id']);
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
```
--------------------------------
### Get Translation or Default
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/methods.md
Retrieves an instance of the translation model for a given locale, always falling back to the configured fallback locale if necessary. Aliases include `getTranslation`.
```APIDOC
translateOrDefault(?string $locale = null)
- Alias of: getTranslation(?string $locale = null, bool $withFallback = null)
- Returns an instance of the translation model for the default or given locale.
- Always uses fallback if needed.
- Examples:
$post->translateOrDefault(); // returns the german translation model
$post->translateOrDefault('fr'); // returns the french translation model
$post->translateOrDefault('it'); // returns the english translation model
```
--------------------------------
### Get Default Locale
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/methods.md
Returns the current default locale set for the model, or null if no default locale is configured.
```APIDOC
getDefaultLocale()
- Returns the current default locale for the current model or `null` if no default locale is set.
- Example:
$post->getDefaultLocale(); // null
```
--------------------------------
### Get Translation Instance
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/methods.md
Retrieves an instance of the translation model for a given locale, with an option to use the fallback locale if the primary locale is not found. Aliases include `getTranslation`.
```APIDOC
translate(?string $locale = null, bool $withFallback = false)
- Alias of: getTranslation(?string $locale = null, bool $withFallback = null)
- Returns an instance of the translation model for the default or given locale.
- Can use the configured fallback locale if the first locale isn't present.
- Examples:
$post->translate(); // returns the german translation model
$post->translate('fr'); // returns the french translation model
$post->translate('it'); // returns null
$post->translate('it', true); // returns the english translation model
```
--------------------------------
### Get Locale Separator
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/locales-helper.md
Retrieves the configured separator character used to combine language and country codes for locales.
```php
$separator = \Astrotomic\Translatable\Locales::getLocaleSeparator();
```
--------------------------------
### Property Fallback Configuration
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/fallback-locale.md
Enables a feature where translatable attributes will return the value from the fallback locale if the translation for the current locale is empty. This is enabled by default on new installations.
```php
'use_property_fallback' => true,
```
--------------------------------
### Retrieve Posts with Translations
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/scopes.md
Get all posts that have existing translations or eager load the translation relationship. The `withTranslation` method is optimized to load translations only for default and fallback locales.
```php
Post::translated()->get();
```
```php
Post::withTranslation()->get();
```
--------------------------------
### Saving Translatable Attributes to Model
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/usage/forms.md
Provides an example of how to save translatable attributes to a model using the `update()` method with `Request::all()`. Both array syntax and colon notation inputs are handled seamlessly.
```php
public function update(Request $request, Post $post)
{
$post->update($request->all());
}
```
--------------------------------
### Get Translated Attributes
Source: https://github.com/astrotomic/laravel-translatable/blob/main/README.md
Demonstrates how to retrieve translated attributes of a model. It shows fetching translations for a specific locale and how the default locale is used when set.
```php
Post::first()->translate('en')->title; // My first post
App::setLocale('en');
echo $post->title; // My first post
App::setLocale('de');
echo $post->title; // Mein erster Post
```
--------------------------------
### RoleUser Pivot Model
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/usage/pivot-model.md
Example of a custom pivot model extending Laravel's Pivot and using the Translatable trait. It specifies that the model uses an auto-incrementing primary key.
```php
use Illuminate\Database\Eloquent\Relations\Pivot;
use Astrotomic\Translatable\Contracts\Translatable as TranslatableContract;
use Astrotomic\Translatable\Translatable;
class RoleUser extends Pivot implements TranslatableContract
{
use Translatable;
public $incrementing = true;
}
```
--------------------------------
### Get Translated Attributes
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/README.md
Demonstrates how to retrieve translated attributes of a model. You can access translations by specifying the locale or by setting the application's locale.
```php
use Illuminate\Support\Facades\App;
$post = Post::first();
// Access translation by locale
echo $post->translate('en')->title; // My first post
// Set application locale and access directly
App::setLocale('en');
echo $post->title; // My first post
App::setLocale('de');
echo $post->title; // Mein erster Post
```
--------------------------------
### Locales Helper API Documentation
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/locales-helper.md
API documentation for the `\Astrotomic\Translatable\Locales` helper class, detailing its methods for locale management.
```APIDOC
Locales Helper Class:
__construct()
Initializes the Locales helper, loading locales from configuration.
load()
Reloads all locales from the 'translatable.locales' configuration. Useful if the config changes at runtime.
all()
Alias: toArray()
Returns all available locales as a flat array, combining country-specific locales.
Example:
[
'en',
'de',
'es',
'es-MX',
'es-CO',
]
current()
Returns the current locale string.
has(string $locale)
Checks if the given locale is available in the configured set of locales.
Parameters:
$locale: The locale string to check.
Returns: bool
get(string $locale)
Returns the provided locale or null if it's not set.
Parameters:
$locale: The locale string to retrieve.
Returns: string|null
add(string $locale)
Adds the given locale to the set of available locales. The set remains unique; duplicates are ignored.
Parameters:
$locale: The locale string to add.
forget(string $locale)
Removes the given locale from the available locales set. Non-existent locales are ignored.
Parameters:
$locale: The locale string to remove.
getLocaleSeparator()
Returns the configured locale separator (e.g., '-') used to combine language and country codes.
Returns: string
getCountryLocale(string $locale, string $country)
Returns the formatted country-based locale.
Parameters:
$locale: The base language locale.
$country: The country code.
Returns: string
isLocaleCountryBased(string $locale)
Checks if the given locale is a country-specific locale.
Parameters:
$locale: The locale string to check.
Returns: bool
getLanguageFromCountryBasedLocale(string $locale)
Returns the language part of a country-based locale.
Parameters:
$locale: The country-based locale string.
Returns: string
```
--------------------------------
### Replicate with Translations
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/methods.md
Creates a clone of the model, including its associated translations.
```APIDOC
replicateWithTranslations(array $except = null)
- Creates a clone and clones the translations.
- Example:
$replicate = $post->replicateWithTranslations();
```
--------------------------------
### Runtime Configuration of RuleFactory
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/validation-rule-factory.md
Illustrates how to override the default configuration of the `RuleFactory` at runtime by passing parameters to the `make()` method. This allows for dynamic adjustment of the format, delimiters, and applied locales.
```php
RuleFactory::make($rules, RuleFactory::FORMAT_KEY, '{', '}', [
'en',
'de',
]);
```
--------------------------------
### Migrating Existing Table Data
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/faq.md
Demonstrates how to insert existing English attributes into a new translation table and then drop the old columns from the main table.
```php
// We insert the old attributes into the fresh translation table:
\DB::statement("insert into country_translations (country_id, name, locale) select id, name, 'en' from countries");
// We drop the translation attributes in our main table:
Schema::table('posts', function ($table) {
$table->dropColumn('title');
$table->dropColumn('content');
});
```
--------------------------------
### Get Language from Country-Based Locale
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/locales-helper.md
Extracts the base language locale from a country-specific locale string (e.g., 'es' from 'es-MX').
```php
$language = \Astrotomic\Translatable\Locales::getLanguageFromCountryBasedLocale('es-MX');
```
--------------------------------
### Fill Multiple Translations
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/README.md
Illustrates how to create a new model instance with translations for multiple locales simultaneously. This is useful for initial data seeding.
```php
$data = [
'author' => 'Gummibeer',
'en' => ['title' => 'My first post'],
'fr' => ['title' => 'Mon premier post'],
];
$post = Post::create($data);
echo $post->translate('fr')->title; // Mon premier post
```
--------------------------------
### Laravel Translatable Version Compatibility
Source: https://github.com/astrotomic/laravel-translatable/blob/main/README.md
This table outlines the compatibility of different versions of the Laravel Translatable package with specific Laravel and PHP versions. It helps users select the correct package version based on their project's environment.
```markdown
| Package | Laravel | PHP |
| :------------------ | :---------------------------- | :-------- |
| **v11.16** | `9.* / 10.* / 11.* / 12.*` | `^8.0` |
| **v11.13 - v11.15** | `9.* / 10.* / 11.*` | `^8.0` |
| **v11.12 - v11.12** | `8.* / 9.* / 10.*` | `^8.0` |
| **v11.10 - v11.11** | `8.* / 9.*` | `^8.0` |
| **v11.6 - v11.9** | `5.8.* / 6.* / 7.* / 8.*` | `>=7.2` |
| **v11.4 - v11.5** | `5.6.* / 5.7.* / 5.8.* / 6.*` | `>=7.1.3` |
| **v11.0 - v11.3** | `5.6.* / 5.7.* / 5.8.*` | `>=7.1.3` |
```
--------------------------------
### Translation Autoloading Configuration
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/methods.md
Manages the autoloading of translations when the `toArray()` method is called. Configuration is controlled by `to_array_always_loads_translations`.
```APIDOC
static enableAutoloadTranslations()
- Forces to load all translations when `toArray()` is called.
```
```APIDOC
static disableAutoloadTranslations()
- Disables translation autoloading, returning only parent attributes when `toArray()` is called.
```
```APIDOC
static defaultAutoloadTranslations()
- Resets the translation autoloading behavior to the default logic.
```
--------------------------------
### Selecting a Model by Translated Field
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/faq.md
Shows how to query for a model based on a translated field using Eloquent's `whereHas` method.
```php
Post::whereHas('translations', function ($query) {
$query
->where('locale', 'en')
->where('title', 'My first post');
})->first();
```
--------------------------------
### Fill Multiple Translations with Wrapper
Source: https://github.com/astrotomic/laravel-translatable/blob/main/README.md
Explains how to use a wrapper property (defined in the config) to group multiple translations when creating a new model instance. This provides a more organized way to handle bulk translations.
```php
// config/translatable.php
// 'translations_wrapper' => 'translations',
$data = [
'author' => 'Gummibeer',
'translations' => [
'en' => ['title' => 'My first post'],
'fr' => ['title' => 'Mon premier post'],
],
];
$post = Post::create($data);
echo $post->translate('fr')->title; // Mon premier post
```
--------------------------------
### Fill Multiple Translations with Wrapper
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/README.md
Explains how to use a configured wrapper property to group multiple translations when creating a new model instance. This requires setting `translations_wrapper` in the config file.
```php
// config/translatable.php
// 'translations_wrapper' => 'translations',
$data = [
'author' => 'Gummibeer',
'translations' => [
'en' => ['title' => 'My first post'],
'fr' => ['title' => 'Mon premier post'],
],
];
$post = Post::create($data);
echo $post->translate('fr')->title; // Mon premier post
```
--------------------------------
### Fixing MySQL Foreign Key Errors (InnoDB)
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/faq.md
Provides solutions for MySQL errors related to foreign key constraints, specifically when using the MyISAM engine. It shows how to update existing tables or set the engine for new tables.
```php
public function up()
{
DB::statement('ALTER TABLE countries ENGINE=InnoDB');
}
public function down()
{
DB::statement('ALTER TABLE countries ENGINE=MyISAM');
}
```
```php
Schema::create('language_translations', function(Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
// ...
});
```
--------------------------------
### Fill Multiple Translations
Source: https://github.com/astrotomic/laravel-translatable/blob/main/README.md
Shows how to create a new model instance with translations for multiple locales simultaneously. This simplifies the process of seeding data with multilingual content.
```php
$data = [
'author' => 'Gummibeer',
'en' => ['title' => 'My first post'],
'fr' => ['title' => 'Mon premier post'],
];
$post = Post::create($data);
echo $post->translate('fr')->title; // Mon premier post
```
--------------------------------
### Using RuleFactory to Generate Validation Rules
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/validation-rule-factory.md
Demonstrates how to use the `RuleFactory` to create validation rules for translated attributes. The factory takes an array of rules with placeholder keys and expands them into rules for each configured locale.
```php
$rules = RuleFactory::make([
'translations.%title%' => 'sometimes|string',
'translations.%content%' => ['required_with:translations.%title%', 'string'],
]);
$validatedData = $request->validate($rules);
```
--------------------------------
### TranslatableProtected Interface
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/interface.md
Defines protected methods for handling translatable attributes, including checking for empty values and saving translations. These methods are crucial for the package's internal logic.
```php
interface TranslatableProtected
{
// detect if a given translation attribute value is empty or not
protected function isEmptyTranslatableAttribute(string $key, $value): bool;
// save all attached translations
protected function saveTranslations(): bool;
}
```
--------------------------------
### Translatable Interface API
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/interface.md
The public API interface for translatable models. It outlines the contract for classes that support translatable attributes, ensuring consistent behavior across different implementations.
```APIDOC
Translatable Interface:
- Describes the public API for translatable models.
- Methods defined here are part of the stable public contract.
- Changes to these methods may result in a major version release.
Protected Methods (Internal Use):
- isEmptyTranslatableAttribute(string $key, $value): bool
- Purpose: Detects if a given translation attribute value is empty.
- Parameters:
- key: The attribute key for the translation.
- value: The value of the translation attribute.
- Returns: True if the attribute value is considered empty, false otherwise.
- saveTranslations(): bool
- Purpose: Saves all attached translations for the model.
- Returns: True if translations were saved successfully, false otherwise.
Note: While the trait might expose more public methods, only those defined or implied by this interface are considered part of the stable public API.
```
--------------------------------
### Form Input with Array Syntax for Locales
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/usage/forms.md
Shows how to structure form inputs using PHP's array syntax (`[]`) to handle translatable fields for different locales. This prevents the need to manipulate form data before saving.
```markup
```
--------------------------------
### Customizing Empty Translation Detection
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/fallback-locale.md
Allows customization of how empty translations are detected for specific attributes by overriding the `isEmptyTranslatableAttribute` method in your model.
```php
protected function isEmptyTranslatableAttribute(string $key, $value): bool
{
switch($key) {
case 'name':
return empty($value);
case 'price':
return !is_number($value);
default:
return is_null($value);
}
}
```
--------------------------------
### Form Input with Colon Notation for Locales
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/usage/forms.md
Illustrates an alternative method for structuring form inputs using colon notation (e.g., `attribute:locale`) to manage translatable fields. In this approach, the attribute name precedes the locale.
```markup
```
--------------------------------
### Format Country-Based Locale
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/locales-helper.md
Constructs a country-specific locale string by combining a language locale with a country code using the configured separator.
```php
$countryLocale = \Astrotomic\Translatable\Locales::getCountryLocale('en', 'GB'); // Returns 'en-GB' if '-' is the separator
```
--------------------------------
### Fill Translatable Fields with Locales
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/usage/forms.md
Demonstrates how to use the overridden fill() method to update translatable fields for multiple locales simultaneously. This is useful when translating a field in a single form submission.
```php
$post->fill([
'en' => [
'title' => 'My first edited post',
],
'de' => [
'title' => 'Mein erster bearbeiteter Beitrag',
],
]);
```
--------------------------------
### Check for Translation
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/methods.md
Checks if a translation exists for the model in the default or a specified locale.
```APIDOC
hasTranslation(?string $locale = null)
- Checks if the post has a translation in the default or given locale.
- Examples:
$post->hasTranslation(); // true
$post->hasTranslation('fr'); // true
$post->hasTranslation('it'); // false
```
--------------------------------
### List Translations by Field
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/scopes.md
Generate an array of post IDs paired with their translated values for a specified field. This is useful for creating select lists or displaying translated data.
```php
Post::listsTranslations('title')->get()->toArray();
```
```json
[
{'id': 1, 'title': 'My first post'},
{'id': 2, 'title': 'My second post'}
]
```
--------------------------------
### Country-Based Fallback Locales Configuration
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/fallback-locale.md
Configures support for country-based locales (e.g., 'es-MX') and allows customization of the separator used between language and country codes.
```php
'locales' => [
'en',
'es' => [
'MX',
'CO',
],
];
```
```php
'locale_separator' => '_',
```
--------------------------------
### App-wide Fallback Locale Configuration
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/fallback-locale.md
Configures the package to use a fallback translation when a specific locale is not found. You can set a default fallback locale or allow the package to use the first available locale.
```json
[
// ...
'use_fallback' => true,
'fallback_locale' => 'en',
// ...
]
```
```json
[
// ...
'use_fallback' => true,
'fallback_locale' => null,
'locales' => [
'en',
'de' => [
'DE',
'AT',
'CH',
],
]
// ...
]
```
--------------------------------
### Set Default Locale
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/methods.md
Sets the default locale for the current model.
```APIDOC
setDefaultLocale(?string $locale)
- Sets the default locale for the current model.
- Example:
$post->setDefaultLocale('fr');
$post->getDefaultLocale(); // 'fr'
```
--------------------------------
### Accessing and Setting Translated Attributes
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/usage/attributes.md
Demonstrates how to access and set translated attributes on a model. It shows accessing attributes using the default locale and a specific locale, as well as updating an attribute.
```php
app()->setLocale('en');
echo $post->title; // My first post
echo $post->{'title:de'}; // Mein erster Beitrag
$post->title = 'My first edited post';
echo $post->title; // My first edited post
```
--------------------------------
### Order Posts by Translation Field
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/scopes.md
Sort the results based on the translated value of a specified field in ascending or descending order.
```php
Post::orderByTranslation('title')->get()
```
--------------------------------
### Check if Locale Exists
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/locales-helper.md
Verifies if a specific locale is present in the configured set of available translation locales.
```php
$exists = \Astrotomic\Translatable\Locales::has('es-MX');
```
--------------------------------
### Eloquent Relation to Translation Model
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/methods.md
This is the Eloquent relation method defining the `HasMany` relationship to the translation model.
```APIDOC
translations()
- Is the eloquent relation method for the `HasMany` relation to the translation model.
```
--------------------------------
### Add a Locale
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/locales-helper.md
Adds a new locale to the set of available translation locales. The method ensures uniqueness, so adding an existing locale has no effect.
```php
\Astrotomic\Translatable\Locales::add('fr');
```
--------------------------------
### TranslatableExists Rule - Basic Usage
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/usage/custom-validation-rule.md
Illustrates the use of the TranslatableExists rule to verify if an attribute value exists in the database. It checks for the presence of the value in the specified model and attribute.
```php
use Astrotomic\Translatable\Validation\Rules\TranslatableExists;
...
$person = new Person(['name' => 'john doe']);
$person->save();
$data = [
'name' => 'john doe',
'email' => 'john@example.com'
];
$validator = Validator::make($data, [
'name' => ['required', new TranslatableExists(Person::class, 'name')],
]);
```
--------------------------------
### Per-Model Fallback Locale
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/fallback-locale.md
Enables or disables the fallback mechanism on a per-model basis by setting the `$useTranslationFallback` property within the model class.
```php
class Post extends Model
{
public $useTranslationFallback = true;
}
```
--------------------------------
### Check if Locale is Country-Based
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/locales-helper.md
Determines whether a given locale string represents a country-specific locale (e.g., 'es-MX').
```php
$isCountryBased = \Astrotomic\Translatable\Locales::isLocaleCountryBased('es-MX');
```
--------------------------------
### TranslatableUnique Rule - Basic Usage
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/usage/custom-validation-rule.md
Demonstrates how to use the TranslatableUnique rule to ensure an attribute is unique across database entries. It checks for the absence of the value in the specified model and attribute.
```php
use Astrotomic\Translatable\Validation\Rules\TranslatableUnique;
...
$person = new Person(['name' => 'john doe']);
$person->save();
$data = [
'name' => 'john doe',
'email' => 'john@example.com'
];
$validator = Validator::make($data, [
'name' => ['required', new TranslatableUnique(Person::class, 'name')],
]);
```
--------------------------------
### TranslatableExists Rule - Translatable Attribute Usage
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/usage/custom-validation-rule.md
Demonstrates how to apply the TranslatableExists rule to a translatable attribute, including the locale. This verifies the existence of a specific translation of an attribute.
```php
use Illuminate\Validation\Rule;
...
$person = new Person(['name' => 'john doe']);
$person->save();
$data = [
'name:en' => 'john doe',
'email' => 'john@example.com'
];
$validator = Validator::make($data, [
'name:en' => ['required', Rule::translatableExists(Person::class, 'name:en')],
]);
```
--------------------------------
### Filter Posts by Translation Value
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/scopes.md
Filter posts based on the translated value of a specific field, supporting exact matches and pattern matching with LIKE. You can also chain `orWhereTranslation` for multiple conditions.
```php
Post::whereTranslation('title', 'My first post')->first();
```
```php
Post::whereTranslation('title', 'My first post')
->orWhereTranslation('title', 'My second post')
->get();
```
```php
Post::whereTranslationLike('title', '%first%')->first();
```
```php
Post::whereTranslationLike('title', '%first%')
->orWhereTranslationLike('title', '%second%')
->get();
```
--------------------------------
### Filter Posts by Translation Locale
Source: https://github.com/astrotomic/laravel-translatable/blob/main/docs/package/scopes.md
Retrieve posts that are translated in a specific locale or not translated in a specific locale. These methods allow for precise filtering based on translation availability.
```php
Post::translatedIn('en')->get();
```
```php
Post::notTranslatedIn('en')->get();
```
--------------------------------
### Save Translated Attributes
Source: https://github.com/astrotomic/laravel-translatable/blob/main/README.md
Illustrates how to save translated attributes for a model instance. It shows updating a translation for a specific locale and persisting the changes to the database.
```php
$post = Post::first();
$post->translate('en')->title = 'My cool post';
$post->save();
$post = Post::first();
echo $post->translate('en')->title; // My cool post
```