spatie/laravel-translatable
Adds HasTranslations to Eloquent models to store translations in JSON columns—no extra tables. Define translatable attributes via PHP 8 attribute or $translatable property, then set/get per-locale values while model accessors return the current app locale.
Pros:
translations table, reducing database complexity and improving performance for read-heavy workloads. Translations are stored as JSON in a single column, leveraging Laravel’s built-in JSON query capabilities (e.g., whereJsonContains, -> notation).HasTranslations trait, requiring minimal boilerplate. Supports both attribute-based (#[Translatable]) and property-based ($translatable) configuration.meta->description), enabling flexible data modeling without schema migrations.whereLocale, whereJsonContainsLocale) for filtering by locale or translation content, which is critical for multilingual applications.Cons:
whereJsonContains) can be slower than indexed columns, especially for large datasets. Indexing JSON columns (e.g., JSON_EXTRACT in MariaDB) may be required for performance-critical queries.name->en) is non-trivial and database-specific (e.g., MySQL 8.0+ generated columns or PostgreSQL JSON operators).Key Use Cases:
Laravel Ecosystem:
actingAs, assertDatabaseHas).cache()->remember), though JSON serialization/deserialization may add overhead.Database Compatibility:
whereJsonContains, -> notation).->>, @> operators).Tooling:
Schema::table()->json()).protected $casts = ['translations' => 'array']).Third-Party Packages:
SoftDeletes, Observables) as long as model methods are namespaced (e.g., getTranslations() vs. getAttributes()).Performance Risks:
whereJsonContainsLocale). Mitigation: Use database-specific optimizations (e.g., MySQL generated columns, PostgreSQL GIN indexes).Data Risks:
json() helper or custom accessors to validate JSON before saving.$model->increment('version')).Maintenance Risks:
dd() or custom error handlers.Key Questions for TPM:
en → es) or dynamic (e.g., API calls to a translation service)?comment: 'This field is translatable')?Laravel Core:
HasTranslations trait; no ORM changes required.whereLocale, whereJsonContainsLocale).required_with:locale, string).TranslationHasBeenSetEvent for observing translation changes.Database:
Schema::table('news_items', function (Blueprint $table) {
$table->json('translations')->nullable(); // Stores all translations
$table->string('fallback_locale')->nullable(); // Optional fallback per model
});
Frontend:
NewsItemResource::collection()).cache()->forever("translations:{$locale}:{$id}")).DevOps:
EXPLAIN ANALYZE in PostgreSQL).2
How can I help you explore Laravel packages today?