Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Translatable Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Schema Simplicity: Eliminates the need for a separate 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).
    • Eloquent Integration: Seamlessly integrates with Eloquent models via the HasTranslations trait, requiring minimal boilerplate. Supports both attribute-based (#[Translatable]) and property-based ($translatable) configuration.
    • Nested Translations: Supports nested JSON structures (e.g., meta->description), enabling flexible data modeling without schema migrations.
    • Query Flexibility: Provides scoped query methods (whereLocale, whereJsonContainsLocale) for filtering by locale or translation content, which is critical for multilingual applications.
    • Fallback Mechanisms: Offers granular control over missing translations (e.g., fallback locales, custom callbacks, or disabling fallbacks per model), improving robustness for edge cases.
  • Cons:

    • JSON Limitations:
      • Query Performance: JSON queries (e.g., 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.
      • Partial Updates: Updating individual translations within a JSON column may trigger full column rewrites, impacting write performance.
    • Schema Rigidity: All translations for a model are stored in a single column, which may complicate:
      • Schema Evolution: Adding/removing translatable fields requires migrations to alter the JSON structure.
      • Partial Indexing: Indexing specific translation keys (e.g., name->en) is non-trivial and database-specific (e.g., MySQL 8.0+ generated columns or PostgreSQL JSON operators).
    • Data Integrity: No built-in validation for translation formats or locales, requiring custom logic (e.g., via model observers or accessors).
    • Migration Complexity: Backfilling translations for existing records may require custom scripts, especially for nested JSON.
  • Key Use Cases:

    • Ideal for content-heavy applications (e.g., CMS, e-commerce, localization platforms) where translations are secondary to core data.
    • Suitable for dynamic or infrequently updated translations (e.g., user-generated content, marketing pages).
    • Less ideal for high-frequency, high-concurrency scenarios (e.g., real-time systems) where JSON write performance is critical.

Integration Feasibility

  • Laravel Ecosystem:

    • Native Support: Works out-of-the-box with Laravel’s Eloquent, Query Builder, and JSON column features. No need for additional ORM layers or database abstractions.
    • Testing: Includes built-in test suite and integrates with Laravel’s testing helpers (e.g., actingAs, assertDatabaseHas).
    • Caching: Compatible with Laravel’s cache layer (e.g., cache()->remember), though JSON serialization/deserialization may add overhead.
  • Database Compatibility:

    • MySQL 5.7+: Recommended for JSON column support (e.g., whereJsonContains, -> notation).
    • PostgreSQL: Supports JSON/JSONB columns with similar query capabilities (e.g., ->>, @> operators).
    • SQLite: Limited JSON query support; may require custom accessors or raw SQL.
    • Legacy Databases: Older MySQL/MariaDB versions may lack JSON functions, requiring workarounds (e.g., serialized strings).
  • Tooling:

    • Migrations: Supports standard Laravel migrations (e.g., Schema::table()->json()).
    • Model Casting: Works with Laravel’s attribute casting (e.g., protected $casts = ['translations' => 'array']).
    • APIs: Compatible with Laravel Sanctum/Passport for securing translation endpoints.
  • Third-Party Packages:

    • Conflict Risk: Low risk of conflicts with other Eloquent traits (e.g., SoftDeletes, Observables) as long as model methods are namespaced (e.g., getTranslations() vs. getAttributes()).
    • UI Libraries: Integrates with frontend libraries like Vue I18n or React Intl via API endpoints.

Technical Risk

  • Performance Risks:

    • Read-Heavy Workloads: JSON queries may degrade under heavy filtering (e.g., whereJsonContainsLocale). Mitigation: Use database-specific optimizations (e.g., MySQL generated columns, PostgreSQL GIN indexes).
    • Write-Heavy Workloads: Frequent updates to JSON columns can cause table locks or slowdowns. Mitigation: Batch updates or use database transactions.
    • Memory Usage: Large JSON payloads (e.g., deeply nested translations) may increase memory usage during serialization/deserialization.
  • Data Risks:

    • Corruption: Malformed JSON in the column can break queries. Mitigation: Use Laravel’s json() helper or custom accessors to validate JSON before saving.
    • Schema Drift: Adding/removing translatable fields requires migrations, which may break existing queries. Mitigation: Document schema changes and use feature flags for gradual rollouts.
    • Concurrency: Race conditions during simultaneous translation updates. Mitigation: Use database transactions or optimistic locking ($model->increment('version')).
  • Maintenance Risks:

    • Package Maturity: While stable (v6 as of 2026), long-term support depends on Spatie’s roadmap. Mitigation: Monitor changelogs and test upgrades.
    • Custom Logic: Fallback behaviors or nested JSON handling may require custom code. Mitigation: Abstract logic into services or traits.
    • Debugging: JSON-based translations can obscure errors (e.g., "undefined index" in nested keys). Mitigation: Use Laravel’s dd() or custom error handlers.
  • Key Questions for TPM:

    1. Performance Requirements:
      • What is the expected read/write ratio for translations? Are there queries that must run in <100ms?
      • Will translations be stored in a single column, or should we consider a hybrid approach (e.g., separate table for frequently queried fields)?
    2. Data Volume:
      • How many translations per record? How many records will use this feature?
      • Are there fields that should not be translatable (e.g., IDs, timestamps)?
    3. Localization Strategy:
      • Will fallbacks be static (e.g., enes) or dynamic (e.g., API calls to a translation service)?
      • Are there locale-specific validation rules (e.g., length constraints for Japanese vs. English)?
    4. Schema Design:
      • Should translatable fields be marked in migrations (e.g., comment: 'This field is translatable')?
      • How will we handle backfilling translations for existing records?
    5. Testing:
      • Should we write custom tests for fallback behaviors and nested JSON?
      • How will we test edge cases (e.g., malformed JSON, missing locales)?
    6. Monitoring:
      • What metrics should we track (e.g., JSON query latency, fallback usage)?
      • How will we alert on schema drift or performance degradation?

Integration Approach

Stack Fit

  • Laravel Core:

    • Eloquent: Native integration with HasTranslations trait; no ORM changes required.
    • Query Builder: Supports JSON queries and scoped methods (whereLocale, whereJsonContainsLocale).
    • Validation: Can be extended with custom rules (e.g., required_with:locale, string).
    • Events: Supports TranslationHasBeenSetEvent for observing translation changes.
  • Database:

    • Recommended: MySQL 8.0+ or PostgreSQL (for JSON query optimizations).
    • Fallback: MariaDB 10.2.3+ or SQLite (with limitations).
    • Schema Example:
      Schema::table('news_items', function (Blueprint $table) {
          $table->json('translations')->nullable(); // Stores all translations
          $table->string('fallback_locale')->nullable(); // Optional fallback per model
      });
      
  • Frontend:

    • APIs: Expose translations via Laravel API resources (e.g., NewsItemResource::collection()).
    • Caching: Cache translations at the locale level (e.g., cache()->forever("translations:{$locale}:{$id}")).
    • Frontend Libraries: Sync with Vue I18n/React Intl via API responses.
  • DevOps:

    • CI/CD: Test migrations and JSON schema changes in pipelines.
    • Backups: Ensure JSON columns are included in backups (standard for Laravel).
    • Monitoring: Track JSON query performance (e.g., EXPLAIN ANALYZE in PostgreSQL).

Migration Path

  1. Assessment Phase:
    • Audit existing models to identify translatable fields.
    • Benchmark JSON vs. relational storage for critical queries.
    • Document fallback and edge-case requirements.

2

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony