spatie/laravel-translatable
Adds a HasTranslations trait to Eloquent models to store translations as JSON in the same table (no extra tables). Define translatable attributes via PHP attribute or $translatable, then set/get translations per locale and auto-resolve by app locale.
Pros:
translations table by storing translations as JSON in a single column, reducing database complexity.#[Translatable]) and traditional $translatable array declarations, accommodating modern Laravel (PHP 8+) and legacy codebases.meta->description), useful for hierarchical data (e.g., CMS content, localized metadata).whereLocale, whereJsonContainsLocale, etc.), enabling efficient filtering by translation attributes.allowNullForTranslation config).Cons:
LONGTEXT in MySQL), which may limit schema migrations or indexing strategies.whereJsonContainsLocale) can be less performant than joins on dedicated tables, especially at scale.Rule::requiredIf for translations).cache()->remember) for translated attributes.saving, updating) or JSON column mutations (e.g., spatie/laravel-activitylog).spatie/laravel-medialibrary if translations are stored in separate columns.JSON_VALID() in MySQL).json_encode() checks before saving).JSON) may require downtime or backup strategies.whereJsonContainsLocale may become slow if the translations column is large or unindexed. Test with production-like data volumes.select() to limit columns where possible.app()->getLocale()) may not handle missing translations gracefully. Explicitly define fallbacks in the model.null values).Rule::required, Rule::string).App::setLocale() and translation helpers (e.g., __()).BlogPost, Product) to test:
#[Translatable]) and property ($translatable) declarations to compare ergonomics.title, description).meta->keywords, specs->dimensions).translations table) to JSON format:
// Example: Migrate from a `translations` table to JSON column
DB::table('translations')->chunk(100, function ($translations) {
foreach ($translations as $translation) {
$model = Model::find($translation->model_id);
$model->setTranslation($translation->column, $translation->locale, $translation->value);
$model->save();
}
});
composer require spatie/laravel-translatable:^6.14 to pin to a stable release.json and pdo extensions are enabled.How can I help you explore Laravel packages today?