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 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.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Simplicity: Eliminates the need for a separate translations table by storing translations as JSON in a single column, reducing database complexity.
    • Flexibility: Supports both PHP attributes (#[Translatable]) and traditional $translatable array declarations, accommodating modern Laravel (PHP 8+) and legacy codebases.
    • Nested Translations: Enables JSON path-based translations (e.g., meta->description), useful for hierarchical data (e.g., CMS content, localized metadata).
    • Query Scopes: Provides rich query capabilities (whereLocale, whereJsonContainsLocale, etc.), enabling efficient filtering by translation attributes.
    • Laravel Integration: Seamlessly integrates with Eloquent, Laravel’s ORM, and validation systems (e.g., allowNullForTranslation config).
    • Performance: JSON operations are optimized for modern databases (MySQL 5.7+, PostgreSQL), with minimal overhead for read/write operations.
  • Cons:

    • Schema Rigidity: Requires JSON-compatible columns (e.g., LONGTEXT in MySQL), which may limit schema migrations or indexing strategies.
    • Query Complexity: Advanced JSON queries (e.g., whereJsonContainsLocale) can be less performant than joins on dedicated tables, especially at scale.
    • Atomicity: JSON updates are not atomic at the row level (e.g., partial updates may fail silently if the JSON structure is invalid).
    • Tooling Limitations: Some ORM tools (e.g., migrations, seeders) may not handle JSON translations intuitively compared to relational tables.

Integration Feasibility

  • Laravel Ecosystem:
    • Compatibility: Works with Laravel 10–13 (as of v6.14.0) and PHP 8.1+. Backward compatibility is maintained for older versions.
    • Testing: Comprehensive test suite (CI/CD integrated) ensures reliability. No breaking changes in recent releases.
    • Validation: Integrates with Laravel’s validation pipeline (e.g., Rule::requiredIf for translations).
    • Caching: Works with Laravel’s cache drivers (e.g., cache()->remember) for translated attributes.
  • Third-Party Packages:
    • Potential Conflicts: May interact with packages using Eloquent events (e.g., saving, updating) or JSON column mutations (e.g., spatie/laravel-activitylog).
    • ORM Extensions: Compatible with packages like spatie/laravel-medialibrary if translations are stored in separate columns.
  • Database:
    • Requirements: MySQL 5.7+, PostgreSQL 10+, or SQLite 3.35+ (JSON support). Avoid older databases without JSON functions.
    • Indexing: JSON columns cannot be indexed directly for translations, limiting query performance on large datasets.

Technical Risk

  • Data Corruption:
    • JSON Validation: Invalid JSON in the translations column (e.g., due to malformed updates) could corrupt data. Mitigate with:
      • Database-level constraints (e.g., JSON_VALID() in MySQL).
      • Application-level validation (e.g., json_encode() checks before saving).
    • Migration Risks: Schema changes (e.g., altering a column to JSON) may require downtime or backup strategies.
  • Performance:
    • Large Datasets: Queries with whereJsonContainsLocale may become slow if the translations column is large or unindexed. Test with production-like data volumes.
    • Memory Usage: Loading models with extensive translations could increase memory usage. Use select() to limit columns where possible.
  • Localization Edge Cases:
    • Fallback Logic: Default locale fallback (e.g., app()->getLocale()) may not handle missing translations gracefully. Explicitly define fallbacks in the model.
    • Dynamic Locales: Applications with runtime locale changes (e.g., user preferences) must ensure translations are fetched efficiently.
  • Testing:
    • Translation Coverage: Unit tests should verify:
      • JSON serialization/deserialization.
      • Locale fallbacks and edge cases (e.g., null values).
      • Query scopes with complex conditions.
    • Integration Tests: Test with real database connections to catch JSON-related issues.

Key Questions

  1. Schema Design:
    • Are existing models using JSON columns, or will this require new migrations? How will we handle backward compatibility?
    • Will translations be stored in the same table as other data, or will we create dedicated tables for non-translatable attributes?
  2. Performance:
    • What is the expected scale (e.g., number of translations per model, query patterns)? Are there benchmarks for similar workloads?
    • Can we index specific translation fields (e.g., using generated columns in MySQL) to improve query performance?
  3. Localization Strategy:
    • How will we handle dynamic locales (e.g., user-specific translations)? Will we use middleware or model-level logic?
    • Are there requirements for translation validation (e.g., minimum length, allowed characters)?
  4. Tooling:
    • How will we manage translations in development (e.g., seeding, translation files)? Will we use Laravel’s built-in localization or a separate tool (e.g., Crowdin)?
    • Are there plans to expose translations via APIs (e.g., GraphQL, REST)? How will we handle versioning or diffs?
  5. Maintenance:
    • What is the strategy for handling breaking changes (e.g., if the package drops PHP 8.1 support)?
    • How will we monitor for JSON corruption or performance regressions in production?

Integration Approach

Stack Fit

  • Laravel Core:
    • Eloquent Models: Ideal for applications using Eloquent (e.g., CMS, e-commerce, SaaS platforms with multilingual content).
    • Validation: Works seamlessly with Laravel’s validation rules (e.g., Rule::required, Rule::string).
    • Localization: Integrates with Laravel’s App::setLocale() and translation helpers (e.g., __()).
    • APIs: Compatible with Laravel Sanctum/Passport for securing translation endpoints.
  • Frontend:
    • JavaScript Frameworks: Translations can be passed to Vue/React via API responses or server-side rendering (e.g., Inertia.js).
    • Static Sites: Useful for generating localized static content (e.g., with Laravel Vapor or Netlify).
  • Database:
    • MySQL/PostgreSQL: Preferred for JSON support and performance.
    • SQLite: Supported but may lack advanced JSON features for large datasets.
    • NoSQL: Not applicable; this package is database-agnostic but optimized for SQL.

Migration Path

  1. Assessment Phase:
    • Audit existing models to identify translatable fields and their current storage (e.g., separate tables, columns).
    • Evaluate database compatibility (e.g., JSON functions, indexing).
  2. Pilot Implementation:
    • Start with a non-critical model (e.g., BlogPost, Product) to test:
      • JSON column migrations.
      • Translation workflows (e.g., admin panel, API).
      • Query performance.
    • Use both attribute (#[Translatable]) and property ($translatable) declarations to compare ergonomics.
  3. Incremental Rollout:
    • Phase 1: Migrate models with simple translations (e.g., title, description).
    • Phase 2: Add nested translations (e.g., meta->keywords, specs->dimensions).
    • Phase 3: Implement query scopes and validation for translations.
  4. Data Migration:
    • Write a migration script to convert existing translations (e.g., from a 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();
          }
      });
      
    • Backup data before migration and validate post-migration.

Compatibility

  • Laravel Versions:
    • Test with the target Laravel version (e.g., 10/11/12) to catch version-specific issues (e.g., Eloquent changes).
    • Use composer require spatie/laravel-translatable:^6.14 to pin to a stable release.
  • PHP Extensions:
    • Ensure json and pdo extensions are enabled.
    • PHP 8.1+ recommended for attribute support and performance.
  • Database Drivers:
    • Test with the primary database driver (e.g., MySQL, PostgreSQL) and edge cases (e.g., read replicas, connections).
  • Caching:
    • If using Laravel’s cache, ensure translations are cached appropriately (e.g., per-locale or globally).
    • Avoid caching models with dynamic translations (e.g., user-specific locales).

Sequencing

  1. Setup:
    • Install the package: `composer
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai