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

Models Laravel Package

laravel-lang/models

Adds localized names and attributes for Laravel Eloquent models via Laravel Lang. Plug-and-play translations for model labels across multiple languages to improve UI, validation messages, and admin panels. Install with composer and follow the docs for setup.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Native Laravel Integration: Designed for Eloquent models, leveraging Laravel’s ORM patterns (traits, scopes, and relationships) without requiring external dependencies beyond Laravel’s core.
    • Minimal Overhead: Uses a one-to-many relationship between parent models and translation models (e.g., ProductProductTranslation), avoiding complex joins or nested structures.
    • Flexible Storage: Supports attribute-level translations (e.g., name, description) via a dedicated translation table, enabling granular control over which fields are localized.
    • Locale-Aware Scopes: Provides built-in Eloquent scopes (e.g., scopeTranslated(), scopeOrderByTranslation()) for querying translations efficiently, reducing custom query logic.
    • Fallback Mechanism: Implicitly supports fallback locales (e.g., enesdefault) via the HasTranslations trait, aligning with Laravel’s App::setLocale().
    • Type Safety: Introduces LocaleData type hints (PHP 8.0+) for method arguments, improving IDE support and reducing runtime errors.
  • Cons:

    • Hard Dependency on Eloquent: Not suitable for non-Laravel PHP applications or projects using alternative ORMs (e.g., Doctrine).
    • Schema Constraints: Requires a separate translation table per model, which may not align with projects using single-table inheritance (STI) or JSON columns for translations.
    • Limited Query Complexity: While scopes are provided, advanced queries (e.g., full-text search across translated fields) may require custom logic.
    • No Built-in Caching Layer: Translation lookups are database-dependent; caching (e.g., Redis) must be implemented separately.

Integration Feasibility

  • Laravel Version Compatibility:
    • Supports Laravel 10–13 and PHP 8.1–8.5, making it viable for most modern Laravel projects.
    • Backward Compatibility: Minimal risk for existing projects, as it extends rather than modifies core Laravel behavior.
  • Database Schema:
    • Requires two migrations per localized model:
      1. Parent model (unchanged).
      2. Translation model (auto-generated via make:model-translation).
    • Example schema:
      // Parent model (e.g., Product)
      Schema::create('products', function (Blueprint $table) {
          $table->id();
          $table->string('sku');
          $table->timestamps();
      });
      
      // Translation model (auto-generated)
      Schema::create('product_translations', function (Blueprint $table) {
          $table->id();
          $table->foreignId('product_id')->constrained()->onDelete('cascade');
          $table->string('locale')->index();
          $table->string('name')->nullable();
          $table->text('description')->nullable();
          $table->timestamps();
      });
      
  • Code Changes:
    • Minimal: Add use HasTranslations; to parent models and define $translatable fields:
      class Product extends Model
      {
          use HasTranslations;
      
          protected $translatable = ['name', 'description'];
      }
      
    • No Route/Controller Modifications: Localization is handled at the model layer.

Technical Risk

  • Low to Medium:
    • Migration Risk: Schema changes are straightforward but require downtime during deployment. Use Laravel’s migration batching or zero-downtime strategies (e.g., double-writes).
    • Performance Risk:
      • N+1 Queries: Eager loading translations is supported but must be explicitly used (e.g., Product::withTranslations()->get()).
      • Translation Table Bloat: High-cardinality locales (e.g., 50+ languages) may increase database size. Monitor table growth.
    • Edge Cases:
      • Concurrent Writes: Race conditions during translation updates are unlikely but possible if not using transactions.
      • Legacy Data: Migrating existing JSON-based translations to this structure requires custom scripts.
    • Testing Overhead:
      • Locale-Specific Tests: Requires testing translation fallback chains, edge locales (e.g., zh-Hans), and empty translations.
      • CI/CD: Add tests for HasTranslations behavior (e.g., assertTranslated(), assertFallback()).

Key Questions

  1. Locale Strategy:

    • How will locales be determined (user preference, URL, header)? Does this package integrate with Laravel’s App::setLocale()?
    • Answer: Yes, it respects Laravel’s locale resolution but requires explicit locale passing for dynamic contexts (e.g., Product::find(1)->translate('fr')).
  2. Translation Granularity:

    • Should all model fields be translatable, or only specific ones (e.g., name, description)?
    • Answer: Configurable via $translatable array in the model.
  3. Fallback Behavior:

    • What happens if a translation is missing for a locale? Should it fall back to default or return null?
    • Answer: Configurable via fallbackLocales() method or config('lang.models.fallback').
  4. Performance:

    • Will translations be cached (e.g., Redis)? If so, how will cache invalidation be handled?
    • Answer: Not built-in; requires custom implementation (e.g., translated() method events).
  5. Multi-Tenant:

    • Does the package support tenant-aware translations (e.g., tenant_id in translation table)?
    • Answer: No; requires customization (e.g., adding tenant_id to the translation model).
  6. Validation:

    • How will translated fields be validated (e.g., unique constraints per locale)?
    • Answer: Use Laravel’s validation rules with locale-specific logic (e.g., Rule::unique('product_translations')->where('locale', $locale)).
  7. API Contracts:

    • How will translated data be serialized in APIs (e.g., JSON:API, GraphQL)?
    • Answer: Requires custom serializers (e.g., JsonSerializable interface) or API resources.
  8. Internationalization (i18n) vs. Localization (l10n):

    • Does this handle pluralization, date formatting, or RTL languages?
    • Answer: No; use Laravel’s built-in i18n tools (e.g., Str::of($text)->locale($locale)) alongside this package.

Integration Approach

Stack Fit

  • Ideal For:
    • Laravel Monoliths: Projects using Eloquent ORM and Laravel’s service container.
    • Multilingual SaaS: Platforms with user-generated content (e.g., CMS, e-commerce, forums).
    • Greenfield Projects: New applications where schema design can accommodate translation tables.
  • Less Ideal For:
    • Microservices: Requires shared database schema or custom synchronization.
    • Headless CMS: If translations are managed externally (e.g., Strapi, Contentful).
    • Legacy Systems: Projects using raw SQL or non-Eloquent models.

Migration Path

  1. Assessment Phase:

    • Audit existing models to identify translatable fields (e.g., name, description, meta_title).
    • Document current localization strategy (e.g., JSON columns, pivot tables, or manual handling).
  2. Pilot Phase:

    • Start with non-critical models (e.g., Page, Category) to test the package.
    • Generate translation models:
      php artisan make:model-translation Product --fields="name:string,description:text"
      
    • Update parent models to use HasTranslations and define $translatable.
  3. Data Migration:

    • Write a script to extract existing translations (e.g., from JSON columns) into the new structure:
      $products = Product::all();
      foreach ($products as $product) {
          $translations = json_decode($product->translations, true);
          foreach ($translations as $locale => $data) {
              $product->translate($locale, $data);
          }
      }
      
    • Use transactions to avoid data corruption.
  4. Feature Rollout:

    • Gradually enable translations for high-impact models (e.g., Product, Article).
    • Update APIs, views, and admin panels to support translated fields.
  5. Deprecation Phase:

    • Phase out old translation logic (e.g., JSON columns) once all models are migrated.

Compatibility

  • Laravel Ecosystem:
    • Works With: Eloquent, Laravel Scout (for search), Laravel Nova/Panel (for admin UIs).
    • Conflicts: Avoid if using packages that modify Eloquent’s fillable or guarded behavior (e.g., some audit packages).
  • Third-Party Packages:
    • Model Observers: May need adjustments if they assume flat model structures.
    • API Resources: Require updates to include translated fields (e.g., `public function toArray($request) {
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity