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

Translator Laravel Package

vinkla/translator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require vinkla/translator
    

    Publish the config file:

    php artisan vendor:publish --provider="Vinkla\Translator\TranslatorServiceProvider"
    
  2. Model Setup: Extend your Eloquent model with Vinkla\Translator\Traits\Translatable:

    use Vinkla\Translator\Traits\Translatable;
    
    class Post extends Model
    {
        use Translatable;
    
        protected $translatable = ['title', 'content'];
    }
    
  3. First Use Case: Save translations for a model:

    $post = new Post();
    $post->title = 'English Title';
    $post->content = 'English Content';
    $post->translate('es', [
        'title' => 'Título en Español',
        'content' => 'Contenido en Español'
    ]);
    $post->save();
    
  4. Retrieving Translations:

    $post->getTranslation('es', 'title'); // Returns 'Título en Español'
    

Implementation Patterns

Common Workflows

  1. Dynamic Translation Handling: Use translate() to add translations dynamically:

    $post->translate($locale, $attributes);
    
  2. Fallback Logic: Implement fallback locales in config/translator.php:

    'fallback_locales' => ['en', 'es'],
    

    Then retrieve translations with fallback:

    $post->getTranslation('fr', 'title'); // Falls back to 'en' if 'fr' missing
    
  3. Query Scopes: Filter models by translation attributes:

    $posts = Post::whereTranslation('title', 'like', '%Spanish%')->get();
    
  4. Batch Translation Updates: Use updateTranslations() for bulk updates:

    $post->updateTranslations('es', ['title' => 'New Title']);
    
  5. Locale-Specific Validation: Validate translations per locale:

    $validator = Validator::make($request->all(), [
        'title_en' => 'required|string|max:255',
        'title_es' => 'required|string|max:255',
    ]);
    

Integration Tips

  • API Responses: Serialize translations in API responses:
    return response()->json($post->getTranslations());
    
  • Admin Panels: Use the package with admin panels (e.g., Nova, Backpack) for translation management.
  • Middleware: Set default locale via middleware:
    public function handle($request, Closure $next)
    {
        app()->setLocale($request->header('Accept-Language'));
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

  1. Archived Package:

    • No active maintenance; consider alternatives like spatie/laravel-translatable for new projects.
    • Test thoroughly for edge cases (e.g., missing translations).
  2. Database Schema:

    • The package assumes a translations table with columns: translatable_id, locale, attributes.
    • Manual migrations may be needed if the schema differs.
  3. Locale Conflicts:

    • Avoid locale keys with underscores (e.g., en_US)—use hyphens (en-us) to prevent SQL issues.
  4. Performance:

    • Eager-load translations to avoid N+1 queries:
      $posts = Post::withTranslations()->get();
      
  5. Caching:

    • Translations are not cached by default. Implement caching manually if needed:
      Cache::remember("post.{$post->id}.translations", now()->addHours(1), function() use ($post) {
          return $post->getTranslations();
      });
      

Debugging Tips

  • Missing Translations: Check if the translatable array in your model includes all fields you’re translating.

    // Debug:
    dd($post->getTranslations());
    
  • SQL Errors: Verify the translations table exists and has the correct columns. Run:

    php artisan schema:dump
    

    to inspect the schema.

  • Locale-Specific Issues: Ensure the locale is correctly set before querying:

    app()->setLocale('es');
    $post->getTranslation('title'); // Works if locale is 'es'
    

Extension Points

  1. Custom Storage: Override the getTranslationsTable() method to use a custom table:

    protected function getTranslationsTable()
    {
        return 'custom_translations';
    }
    
  2. Translation Events: Listen for translatable.saving and translatable.saved events:

    Event::listen('translatable.saving', function ($model, $locale, $attributes) {
        // Pre-save logic
    });
    
  3. Custom Query Builder: Extend the query builder for advanced filtering:

    public function scopeWhereTranslationLike($query, $field, $value)
    {
        return $query->whereHas('translations', function ($q) use ($field, $value) {
            $q->where('locale', app()->getLocale())
              ->whereJsonContains($field, $value);
        });
    }
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed