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

novius/laravel-translatable

Make Laravel Eloquent models translatable using locale and locale_parent_id. Includes migration macro, Translatable trait, relations for translations (with/without soft-deleted), translate() and getTranslation(), plus withLocale() query scope. Supports Laravel 10–13, PHP 8.2–8.5.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Laravel-native: Seamlessly integrates with Eloquent, leveraging existing ORM patterns (e.g., relationships, query scopes).
    • Simple schema: Uses two fields (locale, locale_parent_id) for translations, avoiding complex joins or pivot tables.
    • Trait-based: Encapsulates translation logic in a reusable trait, reducing code duplication across models.
    • Query flexibility: Supports eager loading (withTranslations), scopes (withLocale), and direct access (getTranslation()).
    • Migration-friendly: Provides a translatable() macro for schema migrations, ensuring consistency.
  • Cons:

    • Single-table storage: All translations share a table, risking performance degradation with high cardinality (e.g., 100 languages × 100,000 posts = 10M rows).
    • No built-in fallback: Requires manual handling of missing locales (e.g., default locale logic must be implemented in the trait or application layer).
    • Limited validation: No native support for locale-specific validation rules (e.g., title length per language).
    • Soft deletes: Parent model soft deletes may orphan translations unless explicitly managed (e.g., cascading deletes).
    • No translation history: Lack of built-in versioning for translations (e.g., tracking changes over time).

Integration Feasibility

  • Laravel Compatibility:
    • Supports Laravel 10–13 and PHP 8.2–8.5, aligning with modern Laravel stacks.
    • Works with Eloquent features like observers, events, and policies (translations inherit parent model behavior).
  • Database:
    • Agnostic to database vendor (MySQL, PostgreSQL, SQLite) but assumes standard SQL compliance.
    • Requires indexes on locale and locale_parent_id for performance (not enforced by the package).
  • Caching:
    • No built-in caching layer; requires manual integration (e.g., Cache::remember) for performance-critical applications.
  • Testing:
    • Includes basic tests but lacks comprehensive coverage (e.g., edge cases like concurrent writes).

Technical Risk

Risk Area Severity Mitigation Strategy
Table bloat High Monitor row count; implement archiving or sharding for large datasets.
Query performance Medium Add indexes on locale and locale_parent_id; test with EXPLAIN for complex queries.
Locale management Medium Enforce locale validation in AppServiceProvider; document fallback rules.
AGPL license High Evaluate alternatives (e.g., spatie/laravel-translatable) if AGPL is incompatible.
No translation history Medium Pair with laravel-auditing or implement custom versioning.
Soft delete conflicts Medium Override trait methods to handle cascading deletes or use translationsWithDeleted.

Key Questions

  1. Scalability:
    • How many languages/translations per record are expected? If >100, consider a separate translations table.
  2. Fallback Strategy:
    • How will missing locales be handled (e.g., default to en, return null, or use user preferences)?
  3. Performance:
    • Will queries frequently filter by locale? If so, ensure proper indexing and test with EXPLAIN.
  4. Alternatives:
    • Why not spatie/laravel-translatable (MIT license, separate table, more features) or knuckleswtf/translatable?
  5. Compliance:
    • Is the AGPL-3.0 license acceptable? If not, plan to fork or use a different package.
  6. Future Needs:
    • Will translations require access control (e.g., per-locale permissions) or auditing (e.g., who edited a translation)?

Integration Approach

Stack Fit

  • Ideal Use Cases:
    • Content-heavy apps: Blogs, CMS platforms, or documentation sites with multilingual support.
    • E-commerce: Product catalogs with localized descriptions/prices (if translation volume is moderate).
    • User-generated content: Forums, reviews, or comments where users may submit content in multiple languages.
    • Regional compliance: Apps requiring localized content for legal or UX reasons (e.g., GDPR language access).
  • Avoid For:
    • High-traffic APIs: Single-table storage may not scale for millions of translations.
    • Complex hierarchies: Nested translations (e.g., post.comments[].reply) require custom logic.
    • Schema-less flexibility: If JSON or NoSQL approaches are preferred (e.g., for dynamic attributes).
    • Proprietary software: AGPL license may be incompatible; consider forking or alternatives like spatie/laravel-translatable.

Migration Path

  1. Assessment:
    • Identify models requiring translations (e.g., Post, Product, Page).
    • Audit existing queries to estimate impact (e.g., SELECT * FROM posts WHERE locale = 'fr').
  2. Schema Migration:
    • Add locale (string, indexed) and locale_parent_id (unsignedBigInteger, nullable) to target tables.
    • Use the translatable() macro in migrations:
      Schema::create('posts', function (Blueprint $table) {
          $table->id();
          $table->translatable(); // Adds locale and locale_parent_id
          $table->string('title');
          $table->text('content');
          $table->timestamps();
      });
      
  3. Model Integration:
    • Apply the Translatable trait to models:
      use Novius\LaravelTranslatable\Traits\Translatable;
      
      class Post extends Model {
          use Translatable;
          protected $translatable = ['title', 'content'];
      }
      
    • Customize behavior if needed (e.g., translatableConfig(), translateAttributes()).
  4. Data Migration:
    • Backfill existing data with locale metadata:
      // Example: Set default locale for existing records
      Post::whereNull('locale')->update(['locale' => 'en', 'locale_parent_id' => \DB::raw('id')]);
      
  5. Testing:
    • Validate CRUD operations with translations (e.g., create a fr translation for an en post).
    • Test edge cases:
      • Deleting a parent record (ensure translations are handled).
      • Retrieving non-existent locales (e.g., getTranslation('it')).
      • Concurrent writes (race conditions on locale_parent_id).

Compatibility

  • Laravel Ecosystem:
    • Observers/Events: Translations inherit parent model events (e.g., created, updated).
    • Scout: Works with Laravel Scout for search (translations must be indexed separately).
    • API Resources: Requires manual handling (e.g., PostResource::withoutWrapping() for nested translations).
  • Third-Party Packages:
    • Admin Panels: Compatible with Nova/DataTables if custom fields are registered for translations.
    • Caching: No built-in support; integrate manually (e.g., Cache::remember('post:1:fr', ...)).
  • Frontend:
    • Works with frontend frameworks (e.g., Vue I18n, React Intl) via API endpoints returning localized data.

Sequencing

  1. Phase 1: Pilot
    • Implement with 1–2 non-critical models (e.g., BlogPost, Page).
    • Test performance and edge cases (e.g., locale fallbacks, soft deletes).
  2. Phase 2: Core Models
    • Expand to critical models (e.g., Product, Category) with monitoring.
    • Optimize queries (e.g., add indexes, cache translations).
  3. Phase 3: Optimization
    • Add validation for locales (e.g., restrict to ['en', 'fr', 'es']).
    • Implement fallback logic (e.g., default to en if fr is missing).
    • Document conventions for developers (e.g., "always translate title and description").

Operational Impact

Maintenance

  • Pros:
    • Low boilerplate: Trait handles most logic; customization is minimal (e.g., translatableConfig()).
    • No external dependencies: Self-contained package with no scheduled updates required.
    • Laravel-native: Leverages existing tooling (e.g., migrations, Eloquent).
  • Cons:
    • Manual updates: AGPL license may require vendor lock-in; monitor for upstream changes.
    • Debugging: STI queries can be opaque (e.g., WHERE locale_parent_id = ? vs. WHERE id = ?).
    • Backward compatibility: Future Laravel versions may require
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver